Looking for a way to make this code more kotlin-li...
# getting-started
j
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
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
Ah, I totally forgot that
when
can be used without an argument! That looks cleaner!
I originally tried
when(str)
but realized that's only for checking equality. Thanks!
e
when
-with-subject can also check
in
but it's the wrong way around for your use
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
}
👌 8