Effective Enums in Kotlin with reverse lookup?
Another option, that could be considered more "idiomatic", would be the following:
companion object {
private val map = Type.values().associateBy(Type::value)
operator fun get(value: Int) = map[value]
}
Which can then be used like Type[type]
.
It makes not much sense in this case, but here is a "logic extraction" for @JBNized's solution:
open class EnumCompanion<T, V>(private val valueMap: Map<T, V>) {
fun fromInt(type: T) = valueMap[type]
}
enum class TT(val x: Int) {
A(10),
B(20),
C(30);
companion object : EnumCompanion<Int, TT>(TT.values().associateBy(TT::x))
}
//sorry I had to rename things for sanity
In general that's the thing about companion objects that they can be reused (unlike static members in a Java class)
we can use find
which Returns the first element matching the given predicate, or null if no such element was found.
companion object {
fun valueOf(value: Int): Type? = Type.values().find { it.value == value }
}
First of all, the argument of fromInt()
should be an Int
, not an Int?
. Trying to get a Type
using null will obviously lead to null, and a caller shouldn't even try doing that. The Map
has also no reason to be mutable. The code can be reduced to:
companion object {
private val map = Type.values().associateBy(Type::value)
fun fromInt(type: Int) = map[type]
}
That code is so short that, frankly, I'm not sure it's worth trying to find a reusable solution.