Access members of anonymous object inside class instance

Hello everyone,

While I was reading in the language Docs, I stumbled upon this sytax :

val wildObject = object {
    val x = "hello"
} 

println(wildObject.x)

I have found several uses of this syntax especially in organizing my code like grouping Observables, Views, Models … In such objects.

However I was trying to use the following syntax and it wouldn’t work.

I can’t access any of vipViews’ members.

What am I doing wrong? Is this behavior normal ?

Yes, this is normal. If you use an anonymous object as part of the public API of a class, the type of the corresponding property is the base type of the anonymous object (Any in this case), and you can’t access any members which are not defined in the base type.

So I should use an interface and implement it in my anonymous object ?

It may be better to use a non-anonymous data class as a container for the objects.

1 Like