![](/img/trans.png)
[英]Is it possible to implement custom destructuring for non data class in Kotlin?
[英]implement inequality symbols for a custom class in kotlin
我有這個 class:
class Dog<T: Comparable<T>>(private val name: T, private val weight: T): Comparable<Dog<T>> {
override fun compareTo(other: Dog<T>): Int {
TODO("Not yet implemented")
}
override fun equals(other: Any?): Boolean {
return (other is Dog<*>) && (other.weight == weight)
}
}
我想根據weight
比較任意兩只狗,而不是這樣的名字:
fun main() {
val dog1 = Dog("Dog1", 10)
val dog2 = Dog("Dog2", 11)
println(dog1 > dog2)
println(dog1 <= dog2)
}
我不知所措,無法實現compareTo
function。如果您能提供幫助,我將不勝感激。
如果weight
需要通用,你可以試試這個Dog
class:
class Dog<T : Comparable<T>>(private val name: String, private val weight: T): Comparable<Dog<T>> {
override fun compareTo(other: Dog<T>): Int {
return weight.compareTo(other.weight)
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is Dog<*>) return false
return name == other.name && weight == other.weight
}
}
只要確保您的weight
已正確實施compareTo()
function 即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.