how can I use when guard conditions with multiple ...
# getting-started
b
how can I use when guard conditions with multiple value branches? e.g.
Copy code
when(enum) {
    CASE1, CASE2, CASE3 if otherCondition ->
}
1
y
It's kind of unclear which one the condition should apply to. Regardless, you could write something like:
Copy code
when(enum) {
    in listOf(CASE1, CASE2, CASE3) if otherCondition ->
}
b
thank you
k
This is good in most situations, but be aware that there are performance implications which may matter in a part of the code that is called very frequently. When using multiple-valued branches, when using enums, Kotlin generates a TABLESWITCH bytecode operation which is quite fast. On the other hand, if you use
in listOf(CASE1, CASE2, CASE3)
, Kotlin will: 1. Allocate an array 2. Allocate a
List
and wrap the array 3. Call
contains
The performance hit may not be noticeable so it's worth profiling.
b
yeah, figured as much
at least the list should be faster than a set in this case and quick to allocate
I suppose this gets allocated into a fixed size array in a contiguous memory region
k
You can save a few bytes of bytecode by doing
in arrayOf
instead, but it's probably not worth it, as
listOf
seems to be more idiomatic. On the other hand, if it was primitive types, it would be better to use
in intArrayOf
to avoid boxing.
b
good call
thank you
m
regardless, in this specific case, if you are on the JVM, its probably a good idea to make a compile time constant EnumSet<EnumType>.
in SET_OF_ENUMS if(condition) ->
🙌 1