Ragunath Jawahar
Ragunath Jawahar

Reputation: 19733

Accessing properties of enclosing class

How do I access the properties of an enclosing class? I am working with singletons in Kotlin.

private object IndeterminateAnimationListener : Animation.AnimationListener {
    override fun onAnimationStart(animation: Animation?) {}

    override fun onAnimationEnd(animation: Animation?) {
        // How do I access the properties of the enclosing
        // from here? 
    }

    override fun onAnimationRepeat(animation: Animation?) {}
}

PS: I can use inner classes, how do I do the same with singletons?

Upvotes: 0

Views: 103

Answers (1)

Andrey Breslav
Andrey Breslav

Reputation: 25777

A singleton can not be inner, because there is only one instance of it, and instances of inner classes keep references to instances of outer (enclosing) classes. Therefore, singleton objects can not hold references to enclosing classes, and can not access their properties.

As a workaround, use anonymous objects, which are not singletons:

class A(val foo: Int) {

    val listener = object : AnimationListenerAdapter { 
        override fun onAnimationEnd(animation: Animation?) {
            println(foo) // access to outer
        }
    }
}

Upvotes: 2

Related Questions