2012-05-12 61 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

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