I use the Kotlin Android Extensions plugin for accessing views from XML. If I understand that properly, the synthetic properties generated for the views are nullable, to be more precise - their type is View!
, meaning that they can be treated as non-null in Kotlin, but actually they can still be null because under the hood findViewById
is called, which is from Java, so Kotlin can't ensure null-safety. This is okay because we can use the ?.
operator.
The problem comes when you need to use these in a lambda because the null value gets captured and you never get the chance to handle the non-null value.
See these two snippets.
In the moment these are executed, view1
is non null, but view2
is null:
//this one crashes
view1.setOnClickListener {
view2.doStuff()
}
//this one works
view1.setOnClickListener {
findViewById<View>(R.id.view2).doStuff()
}
What happens in the first case is that when the line is executed, view2
is null and the lambda captures it as null. So even if view2
is not null anymore when the lambda runs (view1
was clicked), the app crashes.
In the second case, the lambda doesn't capture anything, so even though view2
is null at first, it is retrieved again every time the lambda runs (view1
is clicked).
So the question is: How can I use the synthetic property in lambdas, without the initial value being captured?
Thank you!