Skip to content

Instantly share code, notes, and snippets.

@FrancescoJo
Created March 6, 2019 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrancescoJo/12a609b13a6b7dee3c49cecc05bf99fb to your computer and use it in GitHub Desktop.
Save FrancescoJo/12a609b13a6b7dee3c49cecc05bf99fb to your computer and use it in GitHub Desktop.
interface EnumWithKey<T, K> {
val T.key: K
}
/*
* The reified type parameter lets you call the function without explicitly
* passing the Class-object.
*/
inline fun <reified T : Enum<T>, R> EnumWithKey<T, R>.byKey(key: R): T? {
return enumValues<T>().find { it.key == key }
}
enum class Expr(val operator: String) {
SUM("+"),
MINUS("-"),
// ...
;
companion object : EnumWithKey<PaymentMethodType, String> {
// Just define what the key is
override val Expr.key
get() = operator
}
}
// The extension function byKey could be invoked like this:
Expr.byKey("+")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment