https://kotlinlang.org logo
Title
p

poohbar

01/02/2018, 7:28 PM
val f1 = { it.length == 3}   // T.() -> Boolean
val f2 = { length == 3} .    // (T) -> Boolean
this does not look the same to me
a

Andreas Sinz

01/02/2018, 7:43 PM
inside the lambda, they aren't the same, but for convenience you can call them in 2 different ways
k

kevinmost

01/02/2018, 7:55 PM
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

poohbar

01/02/2018, 7:56 PM
ok
x

xenoterracide

01/02/2018, 11:55 PM
one is a closure the other is not
at least that's how I read it
g

gildor

01/03/2018, 12:52 AM
Both of them are closures/lambdas with the same signature on runtime
x

xenoterracide

01/03/2018, 4:38 AM
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

kevinmost

01/03/2018, 4:39 AM
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

xenoterracide

01/03/2018, 4:42 AM
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

gildor

01/03/2018, 4:48 AM
f1 can be closure too
k

kevinmost

01/03/2018, 4:50 AM
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

gildor

01/03/2018, 4:50 AM
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:
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