如何定义这两个简单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)
}
但 min 和 max 未在 union 方法中编译(因为Number [T]没有min / max)。
你能提供一个优雅的超类,它以一个简洁的,一次只修改一次的样板避免方式处理 mid 和 union 方法吗?
答案 0 :(得分:4)
我认为您正在寻找scala.math.Numeric
类型类:
class Interval[T] (val from: T, val to: T)(implicit num: Numeric[T]) {
import num.{mkNumericOps, mkOrderingOps}
def mid: Double = (from.toDouble + to.toDouble)/2.0
def union(other: Interval[T]) = new Interval(from min other.from, to max other.to)
}