如何定义这两个简单的 Interval 类的样板消除超类?
class IntInterval(val from: Int, val to: Int) {
def mid: Double = (from+to)/2.0
def union(other: IntInterval) = IntInterval(from min other.from, to max other.to)
}
class DoubleInterval(val from: Double, val to: Double) {
def mid: Double = (from+to)/2.0
def union(other: DoubleInterval) = DoubleInterval(from min other.from, to max other.to)
}
我试过
class Interval[T <: Number[T]] (val from: T, val to: T) {
def mid: Double = (from.doubleValue+to.doubleValue)/2.0
def union(other: IntInterval) = Interval(from min other.from, to max other.to)
}
但是最小值和最大值没有在联合方法中编译(因为 Number[T] 没有最小值/最大值)。
你能提供一个优雅的超类,它以一种简洁的、一次性且仅一次的样板代码避免方式处理mid和union方法吗?