https://kotlinlang.org logo
Title
h

harry.singh

10/14/2019, 11:41 AM
Hey guys! Wondering how does Kotlin allows access to members of private anonymous object in a class?
e

Evan R.

10/14/2019, 2:52 PM
I think the object needs to be named to access its members, but if you have a private object in a class only instances of that class should be able to access the members of that object
h

harry.singh

10/15/2019, 7:41 AM
What does it mean that the object needs to be named? In the following example from the documentation, the anonymous object is returned from the function, so I guess the anonymous object being referenced by the function name is what you mean?
class C {
    // Private function, so the return type is the anonymous object type
    private fun foo() = object {
        val x: String = "x"
    }

    // Public function, so the return type is Any
    fun publicFoo() = object {
        val x: String = "x"
    }

    fun bar() {
        val x1 = foo().x        // Works
        val x2 = publicFoo().x  // ERROR: Unresolved reference 'x'
    }
}
It makes sense that members variables are not accessible via
x2
as its type is
Any
but what I don't understand is how are we able to access anonymous object internals via
x1
? I'm more interested in what trick does Kotlin employ to achieve this.