Unlike anonymous inner classes, Java 8 lambdas don't hold references to the enclosing (parent) class. Android N adds support for lambdas.
However, they are implemented in the Jack
compiler using anonymous inner classes for backward compatibility, as the note in the link states.
Does this mean that lambdas in Android classes compiled using Jack (and not retrolambda) will hold references to the enclosing class?
I know that one reason many people were excited about lambdas is to avoid Fragment
or Activity
leaks when using them, but at a cursory glance, it looks like using jack
compiler will not give that benefit.
I think the phrase "anonymous class" shouldn't be interpreted too literally here. In my understanding, the only thing they want to tell us is that Jack generates the classes at compile time (as opposed to the runtime approach of Java 8).
From the JackIrBuilder code I'd guess that the generated IR looks very similar to the bytecode that would be generated by retrolambda.
Jack seems to create a synthetic method containing the lambda body in the enclosing type and passes the reference of the enclosing instance to the generated class' constructor only in those cases where it is needed, i.e. when members of the enclosing instance are captured.
Reference: https://android.googlesource.com/toolchain/jack/+/0af676c4779c5b55fb321f491811516f3d74ed93/jack/src/com/android/jack/ir/impl/JackIrBuilder.java
So, from what I understand, the answer is: only when something needs to be captured from the enclosing instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With