Reputation: 1776
I have a general enum implementation with traditional key-value attributes:
enum class FooEnum(val key : String, val value : Any) {
FOO1("FOO_KEY", "FOO_VALUE"),
FOO2("FOO_KEY2", 0);
companion object {
fun getKeyValuesMap(): Map<String, Any> {
val defaults = HashMap<String, Any>()
for (v in values())
defaults[v.key] = v.value
return defaults
}
}
}
Is there a better "Kotlin" way to achieve the same result of getKeyValuesMap()
?
Upvotes: 1
Views: 1840
Reputation: 691685
fun getKeyValuesMap() = FooEnum.values().associate { it.key to it.value }
Upvotes: 4
Reputation: 170723
mapOf(*values().map { foo -> foo.key to foo.value }.toTypedArray())
I'd consider using a val
instead of fun
, the drawback is that someone could in theory cast the result to MutableMap
or HashMap
and mutate it.
Upvotes: 0