I\'m trying to find the best way to do a \'reverse lookup\' on an enum in Kotlin. One of my takeaways from Effective Java was that you introduce a static map inside the enum
True Idiomatic Kotlin Way. Without bloated reflection code:
interface Identifiable {
val id: T
}
abstract class GettableById(values: Array) where T : Number, R : Enum, R : Identifiable {
private val idToValue: Map = values.associateBy { it.id }
operator fun get(id: T): R = getById(id)
fun getById(id: T): R = idToValue.getValue(id)
}
enum class DataType(override val id: Short): Identifiable {
INT(1), FLOAT(2), STRING(3);
companion object: GettableById(values())
}
fun main() {
println(DataType.getById(1))
// or
println(DataType[2])
}