Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Inner scope - This [duplicate]

Tags:

kotlin

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.

like image 978
Paul Woitaschek Avatar asked Nov 25 '15 22:11

Paul Woitaschek


1 Answers

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.

like image 171
aga Avatar answered Nov 11 '22 09:11

aga