2012-05-12 7 views
5

¿Cómo puedo definir una superclase eliminadora de placa de caldera de estas dos clases simples de intervalo?Intervalo real de Scala, Intervalo int

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

me trataron

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

pero el min y max no se compilen en el método de unión (puesto Número [T] no tiene min/max).

¿Puede dar una superclase elegante que se ocupa tanto de la Unión mediados y métodos en una ordenada, en código de una vez y solamente una vez manera repetitivo-evitando?

Respuesta

4

creo que busca la clase de tipos 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. Acabo de verificarlo en 2.9.2 y no tuve problemas con él. ¿Cuál es tu mensaje de error? (¿Olvidaste el 'import num ...'?) – soc

+0

¡muchas gracias! Funcionó perfectamente. –