I have a question about "exhaustive when expressio...
# announcements
n
I have a question about "exhaustive when expression": if I have an enum value which is guaranteed not to have a specific value, the compiler still insists on a branch for that value. Is there a way to avoid that? Concrete simplified example (which does not compile unless I uncomment the one commented out line):
Copy code
import kotlin.random.Random

enum class Priority { LOW, MEDIUM, HIGH }

fun main() {
    val priority = Priority.values()[Random.nextInt(Priority.values().size)]

    val s1 = when (priority) {
        Priority.LOW -> 1
        Priority.MEDIUM -> 2
        Priority.HIGH -> 3
    }

    val s2: Int
    if (priority == Priority.LOW) {
        s2 = 1
    } else {
        s2 = when(priority) {
//            Priority.LOW -> throw IllegalStateException()
            Priority.MEDIUM -> 2
            Priority.HIGH -> 3
        }
    }

    println("s1=$s1 s2=$s2")
}
I tried that also with 1.4.30 and the new backend but I get the same result
n
thx, added my example to that KT
n
is there a less contrived example? usually the naive exhaustive
when
expression is sufficient
n
My use case was that I have an enum covering 3 cases. 2 of the require some complex actions. Thus, the method contains a sequence of
val s1 = when(value) {... }; ... val s2 = when(value) { ... }
. I do not need these
s1
etc for the third case. Thus, I changed the code to
if (value == Case.SIMPLE) { ... } else { ... complex code from above ...}
. However, I still now have to add branches for
Case.SIMPLE
in all the `when`expressions. I could of course bundle that branch with any of the existing ones, but that makes the code hard to read.