Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin Enum with Custom Property and Converter
abstract class EnumConverter<in V, E: Enum<E>>(
private val valueMap: Map<V, E>
) {
fun fromValue(value: V): E? = valueMap[value]
fun fromValue(value: V?, default: E): E = valueMap[value] ?: default
}
inline fun <V, reified E: Enum<E>> buildValueMap(keySelector: (E) -> V): Map<V, E> =
enumValues<E>().associateBy(keySelector)
inline fun <V, reified E> buildValueMap(): Map<V, E> where E: Enum<E>, E: HasValue<V> =
enumValues<E>().associateBy { it.value }
interface HasValue<out T> {
val value: T
}
enum class Size(override val value: Int): HasValue<Int> {
SMALL(0), MEDIUM(1), LARGE(2);
companion object : EnumConverter<Int, Size>(buildValueMap())
}
// println(Size.fromValue(0)) // SMALL
// println(Size.fromValue(10, Size.LARGE)) // LARGE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.