Skip to content

Instantly share code, notes, and snippets.

@nex3z
Created December 12, 2017 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nex3z/23dfc0e5b4491099cda037fe57569fc9 to your computer and use it in GitHub Desktop.
Save nex3z/23dfc0e5b4491099cda037fe57569fc9 to your computer and use it in GitHub Desktop.
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