Allow _ in exhaustive when

The only way to make when exhaustive (for sealed classes) is to use it as an expression. The problem is, a lot of times there is no result (or in other words, result is Unit).

So I end up writing:

val dummy = when (x) {
  is A -> doA()
  is B -> doB()
  is C -> doC()
}

(the other option is to refactor as a separate function, which is inconvenient in many cases)

Unfortunately, this bothers the compiler because dummy is unused.

My suggestion is to allow special variable _ in exhaustive when

1 Like

I know why you want this. Using when as an expression is the only way (right now) to ensure that the compiler checks that it is exhaustive.
That being said I don’t like your suggestion to handle it as it feels like a hack and not like a feature. Instead I would take a look at this topic. There is a discussion about the same problem. I like @fvasco’s suggestion

when(x) {
    is A -> doA()
    is B -> doB()
    !else
}
2 Likes

Thanks!

I like .let{}, looks better than my approach :slight_smile:

I will switch to using that until there is a better (official?) solution

1 Like

Note that in many cases the when clause is the top level of the function. In that case you can use the expression body to make it elegant:

  fun doSomething(param:Sealed):Unit = when (param) {
    is Sealed.A -> println("A")
    is Sealed.B -> println("B")
  }

The return type declaration is not necessary in this case, but can prevent all kinds of confusion.

would really love to see something like @Wasabi375 posted as a language feature - so i opened a KEEP issue for it to maybe push it a bit: https://github.com/Kotlin/KEEP/issues/204

1 Like