I just made use of Kotlins auto refactor and it basically left me with this:
coverView.viewTreeObserver.addOnPreDrawListener {
coverView.viewTreeObserver.removeOnPreDrawListener(this)
true
}
Which does not work. IntelliJ shows me that this refers to the outer class but not to the OnPreDrawListener. Why is that? The kotlin docs say that this always refer to the inner most scope.
To fix your code you can use object expression instead of lambda here:
coverView.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
coverView.viewTreeObserver.removeOnPreDrawListener(this)
return true
}
})
this expression in function expression (and the lambda you pass to the addOnPreDrawListener method is function expression) allows you to access lambda's closure, i.e. variables declared in its outermost scope, not the lambda itself.
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