Skip to content

Instantly share code, notes, and snippets.

@smtion
smtion / EnumConverter.kt
Created November 29, 2021 01:26 — forked from nex3z/EnumConverter.kt
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)