Skip to content

Instantly share code, notes, and snippets.

@maxost
Last active November 2, 2022 10:37
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save maxost/02ad6feea68cdc2146516efcbca37710 to your computer and use it in GitHub Desktop.
Kotlin: Enum 'contains' and 'valueOf' with default value implementations
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