Modify Local Variables Inside Kotlin Lambdas
From what I already know: When function call completes all the local variables inside it get destroyed. Question is: How come in the below code snippet a lambda can change the valu
Solution 1:
In Android Studio you can use Tools -> Kotlin -> Show Kotlin Bytecode, and then Decompile to see what the corresponding Java code might look like.
You'll then see that color
actually turns into a final IntRef color = new IntRef();
, where IntRef
is a class in the Kotlin runtime that has a public int element
member holding the actual value.
Since color
is a final
reference to an object, your OnCheckedChangeListener
can capture it just fine. The member int
is not final
however, which is why you can assign to it (the compiler turns your color = index
into color.element = index;
).
Solution 2:
It's changed internally to a single element array reference.
Think of it like this:
funinit() {
var color = arrayOf()
color[0] = 0
rg.setOnCheckedChangeListener { group, checkedId ->
val childCount = group.childCount
for (index in0 until childCount) {
val button = group.getChildAt(index)
if (button.id == checkedId) {
color[0] = index
}
}
}
}
That's how it can be accessed after the fact.
Post a Comment for "Modify Local Variables Inside Kotlin Lambdas"