are you limited to 2 levels of nested objects in K...
# getting-started
b
are you limited to 2 levels of nested objects in Kotlin?
1
s
not really 🤔
maybe it has to do with your use of anonymous objects instead of named objects?
r
b
aah, I see, thank you
s
yep, anonymous objects' default type is
Any
inside another object
apparently the compiler will only allow you to access properties of an anonymous object when: 1. you define it within a function (as a local var) 2. you only use it within that function's scope
d
Anonymous objects always have their own type, but if it used for some publicly visible declaration (e.g. in
public val
), its type will be approximated to the first supertype of this anonymous object But if it is used in private declaration, then the approximation won't be applied, so you can actually call members of this object
Copy code
class Some {
    val publicObj/*: Any*/ = object {
        fun foo() {}
    }

    private val privateObj/*: anon object*/ = object {
        fun bar() {}
    }

    fun test() {
        publicObj.foo() // error
        privateObj.bar() // ok
        publicTopLevel.foo() // error
        privateTopLevel.bar() // ok
    }
}

val publicTopLevel/*: Any*/ = object {
    fun foo() {}
}

private val privateTopLevel/*: anon object*/ = object {
    fun bar() {}
}
1
👍 2