Created
March 6, 2019 09:40
-
-
Save FrancescoJo/12a609b13a6b7dee3c49cecc05bf99fb to your computer and use it in GitHub Desktop.
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
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