Kotlin: cannot use const val from companion object in an outer enum class

1.3k Views Asked by At

I have a Kotlin enum class defined like this:

enum class EnumClass(val string: String) {

    VALUE_A(A), // [1]

    VALUE_B(B); // [2]

    companion object {

        const val A = "A"

        const val B = "B"
    }
}

and the compiler gives me following errors in lines [1] and [2]:

Variable 'A' must be initialized
Variable 'B' must be initialized

I can solve this error by extracting the consts to the top-level of source file but I don't like this solution. Is there any other way around this problem?

2

There are 2 best solutions below

1
On BEST ANSWER

I was able to get this to work by fully qualifying A and B:

enum class EnumClass(val string: String) {
    VALUE_A(EnumClass.A), 
    VALUE_B(EnumClass.B); 

    companion object {
        const val A = "A"
        const val B = "B"
    }
}
0
On

This will no longer be allowed in 1.9. See this ticket.

enter image description here