"with" does not work with nested object! Is there any way to achieve it?

Hello everyone,

“with (prefix)” is a very nice feature in Kotlin and I have been using it a lot, but today, I am very disappointed to discover that it does not work with object inside object. For example:

object mom {
object child1 { val name = “1” }
object child2 { val name = “2” }
}

In this case, I want to do something like

with (mom) {
print(child1.name)
print(child2.name)
}

, but it just failed. Is there anyway to do that?

Thank you.

The problem is that with can only access instance members of its receiver object mom whereas the two nested objects child1 and child2 are treated as static members.

Although I wouldn’t recommend it, the only way around it would be to re-expose the nested objects as instance properties:

object mom {
    val ch1 = child1
    val ch2 = child2
    object child1 { val name = "1" }
    object child2 { val name = "2" }
}

fun main(args: Array<String>) {
    with(mom) {
        print(ch1.name)
        print(ch2.name)
    }
}

Thank you, but it would be better if we can remove the 2 unnecessary lines. If it can be something like this is also good.
object mom {
val child1 = object { val name = “1” }
val child2 = object { val name = “2” }
}

But it still seems impossible in Kotlin.

That doesn’t work either though for a different reason.

In Kotlin, whilst you can declare a public property or function which returns an anonymous object, the return type of that property or function will be the object’s direct super-class if it has one or (like here) Any if it doesn’t.

Consequently, since (in this example) Any doesn’t have a member called name you get an ‘unresolved reference’ error when you try to compile it.

This would actually work if child1 and child2 were private properties but then, of course, the with statement would need to be somewhere within the mom object itself, so that those properties would be accessible, which I don’t think is what you want.