Issue with when-expression

In IntelliJ IDEA, the following code produces the compile error Error: ‘when’ expression must be exhaustive, add necessary ‘else’ branch:

     sealed class Foo (x: Int) {}
     class Bar (x: Int): Foo(x) {}
     class Baz (x: Int): Foo(x) {}
 
     fun <T: Foo> quux(x: T): String {
         return when (x) {
             is Foo -> "Foo"
             is Bar -> "Bar"
             is Baz -> "Baz"
         }
     }

But since Foo is a sealed class, then T must be a Foo, Bar or Baz, so the when-expression is exhaustive. Is this a compiler bug?

3 Likes

It seems related to the KT-19645 ticket.

2 Likes

I can’t understand that ticket, but at abreslav’s request, I filed a new ticket: KT-35784

What you posted is basically the same thing, but my ticket also specifies an ability to define additional interface constraints on a generic type and that when should be smart enough to catch all possible subtypes.

1 Like