Home > Software design >  Get Enum type by mapping Enum value always complain null issue Android Kotlin
Get Enum type by mapping Enum value always complain null issue Android Kotlin

Time:10-14

I have enum class and I am mapping by value, when I am return Enum value it always complain about null issue.

ConversationStatus.kt

enum class ConversationStatus(val status: String) {
    OPEN("open"),
    CLOSED("closed");

    companion object {
        private val mapByStatus = values().associateBy(ConversationStatus::status)
        fun fromType(status: String): ConversationStatus {
            return mapByStatus[status]
        }
    }
}

This always complain this issue. How can I fix this? Any recommendation for that. Thanks

enter image description here

CodePudding user response:

There's 3 possible ways to go to. Android Studio is often good at suggested fixes as you can see in the screenshot. It suggests to change the return type to ConversationStatus? which means it might return null. It will become this then:

companion object {
    private val mapByStatus = values().associateBy(ConversationStatus::status)
    fun fromType(status: String): ConversationStatus? {
        return mapByStatus[status]
    }
}

Another way is to tell the compiler that you ensure it will always not be null by adding !! to the return statement. Like this:

companion object {
    private val mapByStatus = values().associateBy(ConversationStatus::status)
    fun fromType(status: String): ConversationStatus {
        return mapByStatus[status]!!
    }
}

This will cause a crash though if you call the function with a status that's not "open" or "closed"

Alternatively you could provide a fall back value. With this I mean that it returns a default value in case you call the function with a string that's not "open" or "closed". If you want that to be OPEN you could do like this:

companion object {
    private val mapByStatus = values().associateBy(ConversationStatus::status)
    fun fromType(status: String): ConversationStatus {
        return mapByStatus[status] ?: OPEN
    }
}
  • Related