Created
December 12, 2017 06:59
-
-
Save nex3z/23dfc0e5b4491099cda037fe57569fc9 to your computer and use it in GitHub Desktop.
Kotlin Enum with Custom Property and Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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