It seems that Kotlin2js compiles lambdas very closely to how they look on JVM platform, in particular:
- mutable variables (free vars) are boxed unnecessarily, even for inline lambdas.
- the usage of named factory functions to instantiate lambdas, instead of plain anonymous functions.
Example:
fun takeThatLambda(func: () -> Int): Int = func() + 1
fun someFunc(): Any {
var mut1 = 0; var mut2 = 0; val immut=0
return takeThatLambda { mut1++ + mut2++ + immut }
}
compiles to:
function someFunc() {
var mut1 = {v: 0}; // boxed var
var mut2 = {v: 0}; // boxed var
var immut = 0;
return takeThatLambda(someFunc$lambda(mut1, mut2, immut));
}
Are there any real reasons to compile lambdas this way, aside from it required less effort due to compatibility with jvm?