Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
        }
    }
}
like image 673
s-hunter Avatar asked Mar 08 '23 05:03

s-hunter


2 Answers

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

like image 63
ruX Avatar answered Apr 25 '23 11:04

ruX


Your code has two spots which the compiler, as a whole, does not really understand:

  1. Inside your when clause, you check whether your variable of type Dog really is Dog.
  2. Inside your 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.

like image 26
s1m0nw1 Avatar answered Apr 25 '23 12:04

s1m0nw1