【问题标题】:Scala Real Interval, Int IntervalScala 实数区间、整数区间
【发布时间】: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)
}

但是 minmax 没有在 union 方法中编译(因为 Number[T] 没有 min/max)。

您能否提供一个优雅的超类,以一种简洁的、一次且仅一次的样板代码避免方式处理 midunion 方法?

【问题讨论】:

    标签: scala superclass boilerplate


    【解决方案1】:

    我认为您正在寻找 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)
    }
    

    【讨论】:

    • 嗯。刚刚在 2.9.2 中验证了它,我对此没有任何问题。你的错误信息是什么? (你忘了import num...吗?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2010-09-22
    • 2016-11-26
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多