声明抽象类时指定子类

时间:2019-11-03 12:11:50

标签: kotlin

kotlin版本:1.3.50

在示例代码中,我想使用compareTo方法仅在相同子类的实例之间进行比较,例如将dog与仅dog进行比较。

我认为,如果compareTo仅接受子类但接受Animal,那会更好。但是我不知道该怎么办。有个好主意吗?

abstract class Animal{
    abstract fun compareTo(other: Animal)
    // I want to implement like `abstract fun compareTo(other: this::class)`
}

class Dog: Animal(){
    override fun compareTo(other: Animal) {
        assert(other is Dog)
        // do something
    }
}

class Cat: Animal(){
    override fun compareTo(other: Animal) {
        assert(other is Cat)
        // do something
    }
}

1 个答案:

答案 0 :(得分:0)

您应该向Animal类添加自引用类型参数:

abstract class Animal<SELF : Animal<SELF>> {
    abstract fun compareTo(other: SELF): Int
}

现在您可以像这样扩展它:

class Dog : Animal<Dog>() {
    override fun compareTo(other: Dog): Int {
        // do something
    }
}
相关问题