Hey Guys, I have enum class and I am mapping by va...
# android
v
Hey Guys, I have enum class and I am mapping by value, when I am return Enum value it always complain about null issue.
Copy code
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]
        }
    }
}
How can i avoid this ?
g
Kotlin can't enforce that all possible strings are mapped here, you could send a string not mapped to anything, so either you consider it's not the enum job to crash and returns a nullable value, either you consider it should never happen and you can assert/throw when it happens.
fun fromType(status: String): ConversationStatus {
return mapByStatus[status]!!
}
or any other more verbose way if you prefer:
fun fromType(status: String): ConversationStatus {
val cv = mapByStatus[status]
assert(cv != null) { "ConversationStatus.fromType cannot handle $status"}
return cv
}
d
or just
Copy code
fun fromType(status: String): ConversationStatus {
  return requireNotNull(mapByStatus[status])
}
v
thanks @Damian Zawadzki, what does requireNotNull mean?
@Grégory Lureau great anwser
d
it ensures that value is not null and returns not null variable that you provide as parameter. If parameter somehow null then exception is thrown.
v
okk great
thanks
d
and additionally the check in requireNotNull ensures that parameter outside will be ensured as not nullable:
Copy code
fun a(a: String?){
        requireNotNull(a)
        a.length //no error without ? after a
    }
by a contract mechanism inside.
v
okkk
b
or
Copy code
fun fromType(status: String): ConversationStatus {
  return mapByStatus.getValue(status)
}
116 Views