Allow _ in exhaustive when


#1

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


#2

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
}

#3

Thanks!

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

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


#4

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.