Last active
November 2, 2022 10:37
-
-
Save maxost/02ad6feea68cdc2146516efcbca37710 to your computer and use it in GitHub Desktop.
Kotlin: Enum 'contains' and 'valueOf' with default value implementations
This file contains hidden or 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
inline fun <reified T : Enum<T>> enumContains(name: String): Boolean { | |
return enumValues<T>().any { it.name == name} | |
} | |
inline fun <reified T : Enum<T>> enumValueOf(name: String, defaultValue: T): T { | |
return try { | |
enumValues<T>().first { it.name == name } | |
} catch (e: NoSuchElementException) { | |
defaultValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment