Object expression in field resolves to kotlin.Any

I don't understand if this is expected behavior

class A {
    val fields = object {
        val hello = "hello"
    fun foo() {
        val hello = fields.hello // unresolved reference: hello
        val f = object {
            val hello = "hello"
        val hello2 = f.hello // compiles fine

Apparently, this.fields resolves to kotlin.Any, while the local val f to the anonymous object of type mypackage.A.foo.<no name specified> which is the same I would expect for A.fields

If you declare the object private, it will work. The reason for this is Java interop: exposing anonymous types is no good in Java

Ah I see; then neither protected would work for the same reason (it requires me to explicitate the type)

Would be nice to have a clear error message here - I'd not have guessed that's what was going on.

1 Like

Here https://youtrack.jetbrains.com/issue/KT-21329 I suggested one more option of this functionality which can avoid using anonymous classes in this case:

As option which avoid publishing anonymous class outside of using block can be also used next semantic: val value = object ClassName {...} by analogue of object declaration.

class Properties(val source: Map<String, String>) {
    val system = object System {
        val os: String by source
        val version: String by source
    val db = object Db {
        val username: String by source
        val password: String by source
        val extended = object Extended {
            val poolSize: String by source