Lambdas/closures compilation question

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?

1 Like

I don’t know for sure, but I assume that it’s because doing it this way preserves the same semantics as on the JVM. If they just used an anonymous js function, it wouldn’t act quite the same.