Search code examples
kotlinenumsinitialization

"Variable must be initialized" for companion object with initializer


I don't understand what is wrong with this code:

enum class Example(val property: Int) {
    ONE(333),
    TWO(444),
    THREE(555);
    init {
        propertyToEnum[property] = this
    }
    companion object {
        private val propertyToEnum = mutableMapOf<Int,Example>()
        fun reverseLookup(property: Int): Example? {
            return propertyToEnum[property]
        }
    }
}

The compiler is flagging an error "Variable 'propertyToEnum' must be initialized" inside the init block, but that variable has an initializer inside the companion object. What is wrong here?


Solution

  • Since the companion object is not initialized until after the enum values, you could change it like this to fill your map only when the companion object is being initialized.

    enum class Example(val property: Int) {
        ONE(333),
        TWO(444),
        THREE(555);
        
        companion object {
            private val propertyToEnum = values().associateBy { it.property }
            fun reverseLookup(property: Int): Example? {
                return propertyToEnum[property]
            }
        }
    }