``` val f1 = { it.length == 3} // T.() -> Boo...
# announcements
p
Copy code
val f1 = { it.length == 3}   // T.() -> Boolean
val f2 = { length == 3} .    // (T) -> Boolean
this does not look the same to me
a
inside the lambda, they aren't the same, but for convenience you can call them in 2 different ways
k
exactly.
(T) -> Boolean
and
T.() -> Boolean
are both "a function that needs one param, a
T
, as an input, and outputs a `Boolean`". It seems very reasonable that they'd both be treated the same way outside of the lambda's scope itself
p
ok
x
one is a closure the other is not
at least that's how I read it
g
Both of them are closures/lambdas with the same signature on runtime
x
but what is f1 closing over? it doesn't need any external context inside the method right? as the object is passed as a parameter, thus not a closure (given my understanding of closures)
k
in Kotlin, a lambda or anonymous class is only a closure if it references something outside of its scope, I believe. Otherwise it doesn't need to hold a reference to the outer scope
x
right so f1 is not a closure
but isn't f2 a closure?
where is length coming from
and btw, that's not kotlin specific that's the very definition of a closure
g
f1 can be closure too
k
f2 doesn't have to be a closure, the
length
can come from the implicit receiver type. Though without any type info stored here, the compiler can't really infer that, I believe. I think you'd have to do something like:
val f2: (T) -> Boolean = { length == 3 }
g
this example just not particularly correct. You should use different syntax to define extension lambda.
Yes, exactly what @kevinmost mentioned, code with example just wrong, but both lambdas are equal in runtime
Something like:
Copy code
val f1: String.() -> Boolean = { length == 3 }
val f2: (String) -> Boolean = { it.length == 3 }
in first case instead of lambda parameter you have implicit receiver in
this
Both of them could be closures, but none of them in this example is closure