我该如何定义一个消除样板的超类,可以应用于这两个简单的Interval类?
我尝试了。
但是,在联合方法中,min和max没有编译(因为Number[T]没有最小/最大值)。
你能提供一个优雅的超类来处理mid和union方法,以一种整洁、避免模板重复编码的方式?
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)
}
但是,在联合方法中,min和max没有编译(因为Number[T]没有最小/最大值)。
你能提供一个优雅的超类来处理mid和union方法,以一种整洁、避免模板重复编码的方式?
import num...
?) - soc