Scala Real Interval,Int Interval

时间:2012-05-12 23:25:48

标签: scala superclass boilerplate

如何定义这两个简单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 方法吗?

1 个答案:

答案 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)
}