【发布时间】:2012-05-21 01:02:36
【问题描述】:
如何定义这两个简单的 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 方法?
【问题讨论】:
标签: scala superclass boilerplate