2012-05-12 16 views
5

Wie definiere ich eine Kesselbelichtungs-eliminierende Superklasse dieser zwei einfachen Intervallklassen?Scala Reales Intervall, Int-Intervall

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

Ich versuchte

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

aber der min und max hat kompiliert nicht in der Vereinigung Methode (seit Anzahl [T] nicht min/max hat).

Können Sie eine elegante Oberklasse zu schaffen, die sowohl mit der Mitte und Vereinigung Methoden in einem sauberen, Code-einmal-und-nur-einmal vorformulierten vermeidenden Art und Weise zu tun hat?

Antwort

4

Ich glaube, Sie suchen die 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. Ich habe es gerade in 2.9.2 verifiziert und ich hatte keine Probleme damit. Was ist deine Fehlermeldung? (Hast du die 'import num ...' vergessen?) – soc

+0

danke so viel! Es hat perfekt funktioniert. –