Hi, why are the results different? ```fun main() {...
# announcements
k
Hi, why are the results different?
Copy code
fun main() {
    val a: () -> Unit = { }
    val b: () -> Unit = { }
    val c = generateLambda()
    val d = generateLambda()

    println(a == b) // false
    println(c == d) // true
}

fun generateLambda(): () -> Unit {
    return { }
}
z
i think it’s because the compiler creates a separate lambda object for each lambda in the source code. The lambdas on line 2 and line 3 are different (they’re each on separate lines), so the compiler generates an object for each. It also generates an object for the lambda inside
generateLambda
. However, because those lambdas don’t capture any variables/properties, it only generates a single instance of each one, which is why calling
generateLambda
multiple times returns the same object. Just a guess, I don’t remember exactly how the latest kotlin compilers actually do lambdas.
👍 2
k
Thanks, yeah, it generates multiple instances if the lambda captures external variables
s
Is it possible if We could figure this out by looking at bytecode?
z
yep
y
IIRC, basically the compiler has an optimisation for lambdas when they don't capture any values, and so in this case
generateLambda
returns a singleton
👍 1
TBH I'd love to see a compiler plugin that has full equality for lambdas based on the code inside of them