https://kotlinlang.org logo
#compiler
Title
# compiler
s

Sam Stone

10/06/2023, 3:53 AM
I notice that in large `when(i)`s, if even one of the branches contains a range check (e.g.
in 1..5
), the Java bytecode will be many
if
-`else`s. Otherwise (all branches are value comparison), it will be a
switch
. If the range is small enough, can't the compiler optimize it to the equivalent of constant checks?
Copy code
when(i) {
    1->{...}
    2->{...}
...
} //Uses switch
when(i) {
    1->{...}
    2->{...}
    in 3..7 ->{...}
...
} //Uses if-else
//Same as:
when(i) {
    1->{...}
    2->{...}
    3,4,5,6,7 ->{...}
...
}//Uses switch