【问题标题】:scala: how to create a generic type which is subtype of all the number classes in scala so that it can include compare methodscala:如何创建一个泛型类型,它是 scala 中所有数字类的子类型,以便它可以包含比较方法
【发布时间】:2009-08-31 14:25:12
【问题描述】:

我正在尝试创建一个泛型类,泛型类型是 Numeric 的子类(以确保我正在处理数字。) 我尝试将“class 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

非常感谢任何帮助。

谢谢,
〜老虎。
我不知道这是一个错误还是我的定义有问题。

【问题讨论】:

标签: generics scala


【解决方案1】:

Scala 的Numeric[T] 使用"Typeclass Pattern"。说class NuVector[T &lt;: Numeric[T]] 真的没有意义。相反,你想要的是class NuVector[T](implicit n: Numeric[T])。

【讨论】:

  • 这方面的捷径是 Scala 2.8 中引入的“上下文绑定”:class NuVector[T : Numeric]。如果此T 在范围内,则可以使用val num = implicitly[Numeric[T]] 获取证据参数。
【解决方案2】:

更好的是,使用class NuVector[T:Numeric]

这也称为上下文绑定,只是class NuVector[T](implicit n: Numeric[T]) 的语法糖

n 实际上是一些综合生成的名称,您无法直接访问

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 2015-03-09
    • 2021-07-31
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2020-03-27
    相关资源
    最近更新 更多