5

如何定义这两个简单的 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] 没有最小值/最大值)。

你能提供一个优雅的超类,它以一种简洁的、一次性且仅一次的样板代码避免方式处理midunion方法吗?

4

1 回答 1

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)
}
于 2012-05-12T23:39:49.253 回答