首页 > 解决方案 > 声明抽象类时指定子类

问题描述

科特林版本:1.3.50

在示例代码中,我想使用compareTo方法仅在同一个子类的实例之间进行比较,例如dogis compare to only 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
    }
}

标签: kotlin

解决方案


您应该向类添加一个自引用类型参数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
    }
}

推荐阅读