Scala Real Interval Interval Interval

How can I define superclasses separating the boiler-plate of these two simple interval classes?

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

I tried

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

but min and max did not compile in the union method (since Number [T] does not have min / max).

Can you imagine an elegant superclass that deals with both mid methods and combining in a neat, once incorrect use of code-code?

+5
source share
1 answer

I think you are looking for scala.math.Numerictypeclass:

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)
}
+4
source

All Articles