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

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


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
as its type is
but what I don't understand is how are we able to access anonymous object internals via
? I'm more interested in what trick does Kotlin employ to achieve this.