Looking for a way to make this code more kotlin-like. Just trying to get more comfortable with the more nuanced syntactical aspects of the language.
My code is like this:
Copy code
val foo: Map<String, String> = if (str.contains(bar1)) {
map1
} else if (str.contains(bar2)) {
map2
} else if (str.contains(bar3)) {
map3
} else {
defaultMap
}
The maps are properties defined in the class that this function is in. There is potential for more maps to be added in the future. This is basically a way for me to select which map to use.
str
is a value passed into this function and is expected to meet 1 of the 3 criteria.
Is there a more clever way to do this?
t
Thomás Horta
09/24/2022, 5:57 AM
This looks like a good case for when statement (which is like a "super-powered" Java switch-case):
Copy code
val foo = when {
str.contains(bar1) -> map1
str.contains(bar2) -> map2
str.contains(bar3) -> map3
else -> defaultMap
}
Since all maps are Map<String, String> you don't really need to declare the type of
foo
j
Joshua Hansen
09/24/2022, 6:19 AM
Ah, I totally forgot that
when
can be used without an argument! That looks cleaner!
Joshua Hansen
09/24/2022, 6:20 AM
I originally tried
when(str)
but realized that's only for checking equality. Thanks!
e
ephemient
09/24/2022, 9:16 AM
when
-with-subject can also check
in
but it's the wrong way around for your use
ephemient
09/24/2022, 9:18 AM
I think it's clearer to write this though
Copy code
when {
bar1 in str -> map1
bar2 in str -> map2
bar3 in str -> map3
else -> defaultMap
}