2012-05-12 28 views
5

如何定义这两个简单Interval类的消除锅炉板的超类?Scala Real Interval,Int 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) 
} 

分钟最大工会方法没有编译(因为数量[T]不具有最小值/最大值)。

你能提供一个优雅的超这既与中期联合交易方法整齐,代号一次且仅一次样板回避呢?

回答

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) 
} 
+0

Mhhh。刚刚在2.9.2中对它进行了验证,并且我没有遇到任何问题。你的错误信息是什么? (你忘了'import num ...'?) – soc

+0

非常感谢!它工作完美。 –