kotlinenumsstatickotlin-companion

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


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?


Solution

  • 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"
        }
    }