kotlin - 声明抽象类时指定子类
问题描述
科特林版本:1.3.50
在示例代码中,我想使用compareTo
方法仅在同一个子类的实例之间进行比较,例如dog
is 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
}
}
解决方案
您应该向类添加一个自引用类型参数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
}
}
推荐阅读
- java - org.openqa.selenium.WebDriverException(端口无效。退出...)
- python - 如何将 df 列拆分为多行和计数(long df)Python / pandas
- c - malloc 意外的内存分配
- r - 使用 ggplot 推断/预测非线性
- c - 允许您打印重复次数最多的数字的函数和数组
- angular - 使用 Angular .TS 在 Goole 图表中显示价值
- python - 按熊猫数据框分组并在每组中选择下一个即将到来的日期
- reactjs - Okta - OAuthError - 无法处理用户名转换。缺少必需的属性。缺少字段电子邮件
- asp.net-core - HTTP 错误 500.19 - 内部服务器错误-0x8007000d
- discord - discord.py 获取频道的 webhook