2012-05-12 14 views
5

Come si definisce una superclasse eliminante piastre di riscaldamento di queste due classi di intervallo semplici?Intervallo reale scala, intervallo intermedi

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

ho cercato

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

ma il min e max non ha compilato nel metodo unione (dal Numero [T] non ha min/max).

Potete fornire un elegante superclasse che si occupa sia con il sindacato metà e metodi in un modo accurato, in codice, una volta-e-solo-una volta modo boilerplate-evitando?

risposta

4

Penso che si sta cercando il scala.math.Numeric typeclass:

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. Appena verificato in 2.9.2 e non ho avuto problemi con esso. Qual è il tuo messaggio di errore? (Hai dimenticato l'importazione num ...?) – soc

+0

grazie mille! Ha funzionato perfettamente. –