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

泛型 – scala:如何创建一个泛型类型,它是scala中所有数字类的

发布时间:2020-12-16 18:53:41 所属栏目:安全 来源:网络整理
导读:我正在尝试创建一个泛型类,其泛型类型是Numeric的子类(以确保我处理数字.) 我尝试将“类NuVector [T:Numeric [T])”作为类def并编译好. 现在我想添加PartiallyOrdered [T].所以我做了以下事情: class NuVector[T:Numeric[T]) extends PartiallyOrdered[T]{
我正在尝试创建一个泛型类,其泛型类型是Numeric的子类(以确保我处理数字.)
我尝试将“类NuVector [T<:Numeric [T])”作为类def并编译好. 现在我想添加PartiallyOrdered [T].所以我做了以下事情:

class NuVector[T<:Numeric[T]) extends PartiallyOrdered[T]
{

 /** Array that stores the vector values.
     */
    val v = new Array [T] (_length)
    /** Range for the storage array.
     */
    private val range = 0 to _length - 1

    def compare(x:T,y:T)(implicit res:Numeric[T]) :Int=
    { 
       res.compare(x,y) 
    } 

   def tryCompareTo [B >: NuVector [T]] (b: B)
        (implicit view$1: (B) => PartiallyOrdered [B]): Option [Int] =
    { 
        compare(x,y) 
    } 

    implicit def castT2Ordering(x:T):Numeric[T]=x.asInstanceOf[Numeric[T]]
    implicit def castB2NuVector [B>:NuVector[T]] (b:B): NuVector[T]=
    {
              b.asInstanceOf[NuVector[T]]
    }

}

它没有编译.
我在编译时得到的错误是:

could not find implicit value for parameter res:Numeric[T]

我使用的Scala版本是2.8

任何帮助是极大的赞赏.

谢谢,
?虎.
我不知道这是一个错误还是我的定义问题.

解决方法

Scala的Numeric [T]使用 “Typeclass Pattern”.说NuVector类[T<:Numeric [T]]并没有多大意义.你想要的是类NuVector [T](隐式n:数字[T]).

(编辑:李大同)

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

    推荐文章
      热点阅读