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()
}
}
}
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
Your code has two spots which the compiler, as a whole, does not really understand:
when
clause, you check whether your variable of type Dog
really is Dog
.when
clause, you also check whether your variable of type Dog
is a Cat
.It's a bit contradictory to the compiler since both types only share a super type with each other. The problem really is that your variable does not explicitly declare its type. As a result of assigning the Dog
instance to your var i
, the compiler infers its type, which of course is Dog
. Everything afterwards makes sense: no need to check for the instance type, it definetly is a Dog
.
To make the code work, you have to declare var i: Animal
, explicitly typed. Also, always consider using val
in favor of var
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With