Pihentagy
08/15/2024, 8:08 AMJoffrey
08/15/2024, 8:11 AMwhen
and ranges:
when (population) {
in 0..<10_000 -> "small"
in 10_000..<100_000 -> "medium"
in 100_000..<1_000_000 -> "large"
else -> "extra large"
}
See this runnable example: https://pl.kotl.in/PzM94ejdIJoffrey
08/15/2024, 8:13 AMwhen
, by the way. You can store those ranges in variables and use them in other ways too.Pihentagy
08/15/2024, 8:26 AMloke
08/15/2024, 9:06 AMwhen (val p = population) {
p < 0 -> error("negative population")
p < 10000 -> "small"
p < 100000 -> "medium"
...
else -> "extra large"
}
Joffrey
08/15/2024, 9:54 AMwhen
(because you may want to match several branches at the same time). You could have several `if`s in sequence, so all matching branches will be run.Joffrey
08/15/2024, 9:57 AMJoffrey
08/15/2024, 9:58 AMwhen
+ ranges.Klitos Kyriacou
08/15/2024, 10:02 AMwhen (val p = population) {
p < 0 -> error("negative population")
...
}
That checks if p
(an Int) is equal to p < 0
(a Boolean). What you wanted is more like this:
val p = population
when {
p < 0 -> error("negative population")
...
}
Pihentagy
08/16/2024, 9:54 AMwhen
)Joffrey
08/16/2024, 9:56 AMwhen
, the conditions are tested sequentially and only the first match is used, hence why I was suggesting multiple `if`s if you need to support multiple matches.