Tag: 密封class

Kotlin中的密封类,不兼容的types错误

我有以下Kotlin代码。 一个叫做Animal的密封类,以及两个对象类Dog和Cat从密封类Animalinheritance。 我是在猫案中的when子句中得到这个错误。 Incompatible types: Cat and Dog 为什么会出现这个错误? 如何在Kotlin中使用密封类来进行这种types的操作? 密封类是做多态的一个好的选择? 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) { var i = Dog i.speak() when(i) { is […]