これら 2 つの単純な Interval クラスのボイラープレートを排除するスーパークラスを定義するにはどうすればよいですか?
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)
}
私は試した
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)
}
ただし、minとmaxはunionメソッドでコンパイルされませんでした(Number[T] には min/max がないため)。
midメソッドとunionメソッドの両方をきちんとしたコード 1 回限りのボイラープレートを回避する方法で処理するエレガントなスーパークラスを提供できますか?