Home > Software engineering >  Unresolved reference while accessing a member of an anonymous object
Unresolved reference while accessing a member of an anonymous object

Time:11-12

I tried to create an object to group some variables, as it is typically done in JavaScript.

val authorization = object {
    val header = "Authorization"
}

fun main() {
    println ("${authorization.header}")
}

But this produces a reference error. The problem seems to be, that the type of authorization is Any and Any does not know header.

How to fix this?

BTW: here is stated that this should work.

CodePudding user response:

What the linked article failed to mention maybe is that this piece of code:

val obj = object {
    val question = "answer"
    val answer = 42
}
println("The ${obj.question} is ${obj.answer}")

is all inside the body of a single method. To be able to use anonymous objects like that from elsewhere they need to be private. So this would work fine:

private val authorization = object {
    val header = "Authorization"
}

fun main() {
    println ("${authorization.header}")
}

I see it does mention it in this related article in section 5 https://www.baeldung.com/kotlin/anonymous-objects

  • Related