Take the following 2 sealed classes, and a function for each:
sealed class MyException : Exception()
class MaximumSizeReached : MyException()
sealed class Transport
class Car : Transport()
fun a(me: MyException) {
when (me) {
is MaximumSizeReached -> { println("a") }
// WHY? Not a sub class of MyException
is IllegalArgumentException -> { println("b") }
// Compiler error: Incompatible types: String and MyException
//is String -> { println("c") }
// WHY? Not a sub class of MyException
is RuntimeException -> { println("d") }
// Base class of MyException
is Exception -> { println("e") }
// Base class of MyException
is Throwable -> { println("f") }
// Base class of MyException
is Any -> { println("g") }
}
}
fun b(t: Transport) {
when (t) {
is Car -> { println("A") }
// WHY? Not a sub class of Transport
is IllegalArgumentException -> { println("B") }
// Compiler error: Incompatible types: String and Transport
//is String -> { println("C") }
// WHY? Not a sub class of Transport
is RuntimeException -> { println("D") }
// WHY? Not a sub class of Transport
is Exception -> { println("E") }
// WHY? Not a sub class of Transport
is Throwable -> { println("F") }
// Base class of Transport
is Any -> { println("G") }
}
}
fun main() {
a(MaximumSizeReached())
b(Car())
}
In both cases, exceptions that are not part of the hierarchy of the sealed class, are allowed in the condition of when
branches. But String
is not, which is expected.
Why are Throwable
and its sub classes always allowed in when
?