Search code examples
kotlinsealed-class

Sealed class in Kotlin, Incompatible types error


I have the following Kotlin code. A sealed class called Animal, and two object classes Dog and Cat inherits from the sealed class Animal. I am getting this error in the when clause in the is Cat case.

Incompatible types: Cat and Dog

Why is it giving this error? How can I use sealed class in Kotlin to this type operations? Is sealed class a good choice for doing polymorphism?

sealed class Animal {
  abstract fun speak()
}

object Dog : Animal() {
    override fun speak() { println("woof") }
}

object Cat : Animal() {
    override fun speak() { println("meow") }
}

fun main(args: Array<String>) {
    var i = Dog
    i.speak()
    when(i) {
        is Dog -> {
            print("Dog: ")
            i.speak()
        }
        is Cat -> {
            print("Cat: ")
            i.speak()
        }
    }
}

Solution

  • The missing part is var i: Animal = Dog

    Basically compiler is complaining about types - Cat is not a subtype of the Dog (but they are both are subtypes of Animal, that's why if you explicitly set base type code will compile and work