加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala Real Interval,Int Interval

发布时间:2020-12-16 18:37:55 所属栏目:安全 来源:网络整理
导读:如何定义这两个简单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: D
如何定义这两个简单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.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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读