Colton Idle
07/14/2022, 7:18 PMenum class Foo(val key: String, val userName: String) {
Bar("bar_item", "Bar For You"),
Baz("baz_item", "Baz For Me"),
OTHER("other", "Other"),
}
fun getTheFoo(key: String): Foo {
return when (key) {
"bar_item" -> Foo.Bar
"baz_item" -> Foo.Baz
"other" -> Foo.OTHER
else -> Foo.OTHER
}
}
Luke
07/14/2022, 7:28 PMreturn Foo.values().firstOrNull { it.key == key } ?: Foo.OTHER
maybe?Colton Idle
07/14/2022, 7:33 PMephemient
07/14/2022, 7:48 PMprivate val fooByKey = Foo.values().associateBy { it.key }
fun getTheFoo(key: String): Foo = fooByKey[key] ?: Foo.OTHER
but with 3 I might leave it as an iterative searchColton Idle
07/14/2022, 7:50 PMYoussef Shoaib [MOD]
07/15/2022, 7:30 AMFoo.values()
, and so it works just like a normal map.Matteo Mirk
07/18/2022, 1:12 PMenum class Foo(val userName: String) {
bar_item("Bar For You"),
baz_item("Baz For Me"),
other("Other")
}
fun getTheFoo(key: String) = try {
Foo.valueOf(key)
} catch (e: IllegalArgumentException) {
Foo.OTHER
}
otherwise if you dislike the try block you could use:
fun getTheFoo2(key: String) =
runCatching { Foo.valueOf(key) }.getOrDefault(Foo.other)
ephemient
07/18/2022, 1:19 PMMatteo Mirk
07/18/2022, 1:23 PM