How do I define a boiler-plate-eliminating superclass 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 the min and max did not compile in the union method (since Number[T] does not have min/max).
Can you provide an elegant superclass which deals with both the mid and union methods in a neat, code-once-and-only-once boilerplate-avoiding way?
I think you are looking for the 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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With