June 2018
Intermediate to advanced
316 pages
6h 34m
English
Capturing lambdas is a really convenient feature of Kotlin that allows you to write code like this:
fun main(args: Array<String>) { var counter = 0 val inc = { counter ++ } inc()}
In the preceding snippet, a lambda changes a local variable of the main function. In Java, we can't do this because local variables are root objects for the garbage collector and we have to use some tricks to work around this. But it works in Kotlin out of the box. Decompiled to Java, this code looks like this:
public static final void main(@NotNull String[] args) { Intrinsics.checkParameterIsNotNull(args, "args"); final IntRef counter = new IntRef(); counter.element = 0; Function0 inc = (Function0)(new Function0() { // $FF: synthetic method // ...
Read now
Unlock full access