Joshua Hansen
09/24/2022, 5:45 AMval 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?Thomás Horta
09/24/2022, 5:57 AMval 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
Joshua Hansen
09/24/2022, 6:19 AMwhen
can be used without an argument! That looks cleaner!Joshua Hansen
09/24/2022, 6:20 AMwhen(str)
but realized that's only for checking equality. Thanks!ephemient
09/24/2022, 9:16 AMwhen
-with-subject can also check in
but it's the wrong way around for your useephemient
09/24/2022, 9:18 AMwhen {
bar1 in str -> map1
bar2 in str -> map2
bar3 in str -> map3
else -> defaultMap
}