What is the idiomatic kotlin way to handle interva...
# getting-started
p
What is the idiomatic kotlin way to handle intervals? Say I have a population variable, and need to branch on: smaller than 10'000, between 10'000 and 100'000, between 100'000 and 1'000'000, above 1'000'000?
j
One way to do this is with a
when
and ranges:
Copy code
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/PzM94ejdI
Ranges like this are not a special construct of the
when
, by the way. You can store those ranges in variables and use them in other ways too.
p
Nice and compact, but what if the provided ranges are not disjuct? (you should write out (almost) every number twice)
l
What about:
Copy code
when (val p = population) {
  p < 0 -> error("negative population")
  p < 10000 -> "small"
  p < 100000 -> "medium"
  ...
  else -> "extra large"
}
👍 1
1
j
@Pihentagy if the ranges are not disjoint (meaning that they overlap), you cannot use a
when
(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.
It the ranges are disjoint, but the bounds are shared between consecutive ranges, then you can use @loke’s suggestion with only comparisons to one side.
If the ranges are disjoint, but don't have the same bounds, then you can use my suggestion with
when
+ ranges.
k
The following doesn't work:
Copy code
when (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:
Copy code
val p = population
when {
  p < 0 -> error("negative population")
  ...
}
👍 1
p
Thanks, @Joffrey. Just wondered, what if you think the ranges should be disjoint, but actually are not. (The answer is that the first matching case is run, when using
when
)
j
I'm sorry I'm not sure what your question is exactly here. Yes, in a
when
, 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.