我想要什么:
data class Customer (val id: Int) : Comparable by id
但是可比对象需要类型参数,这意味着它不能委托给id
。这可行吗?还是我只是因为某种原因而忽略了这个想法?
答案 0 :(得分:1)
我建议这样的事情:
data class Customer(val id: Int) : Comparable<Customer> by IntComparator(id, { it.id })
class IntComparator<T>(private val number: Int, private val getter: (T) -> Int) : Comparable<T> {
override fun compareTo(other: T): Int = this.number.compareTo(getter(other))
}
此示例需要适应您最常见的情况,以使其更加美观。您可以为类,接口,数据元组等创建比较器。
答案 1 :(得分:0)
您可以将val id
用于comparingInt,例如:
class Date(val year: Int, val month: Int, val day: Int) : Comparable<Date> { override fun compareTo(other: Date): Int { return COMPARATOR.compare(this, other) } companion object { private val COMPARATOR = Comparator.comparingInt<Date> { it.year } .thenComparingInt { it.month } .thenComparingInt { it.day } } }
答案 2 :(得分:0)
似乎没有一种很干净的方法,因为不支持在委托构造函数中引用this
(与附加对象一样)。
考虑使用Int属性实现Comparable确实很简单:
class Test (val x: Int = 0) : Comparable<Test> {
override fun compareTo(other: Test) = x - other.x
}
或任何可比较的属性:
class Test (val x: Long = 0) : Comparable<Test> {
override fun compareTo(other: Test) = x.compareTo(other.x)
}
答案 3 :(得分:0)
如果客户只能通过其ID进行比较,则定义类型:
data class Customer (val id: Int) : Comparable<Int> by id