My company code moved finally up to Kotlin 2.1.0 (yay!) and I wanted to give a quick demo of the new features. The else branch in when when it was logically not needed was always bothering me, so I’m glad there is some improvement. However, this seems to work only one level deep:
// Kotlin 2.1.0
sealed interface Animal {
interface Bird: Animal
class Raven: Bird
class Hawk: Bird
interface Mammal: Animal
class Lion: Mammal
class Panda: Mammal
}
fun main() {
val animal: Animal = listOf(Raven(), Hawk(), Lion(), Panda()).shuffled().first()
println("selected ${animal.javaClass.simpleName}")
when(animal) {
is Bird -> println("flies")
is Lion -> println("roars")
is Panda -> println("eats shoots and leaves")
// wants still an else branch...
}
}
The code works as advertised when there is a Mammal branch instead of the sub class branches of Mammal, which is already a huge step in the right direction, but I don’t get why the problem wasn’t solved completely when they were already working on it. It doesn’t seem to be too difficult, right?
What are your thoughts?