Scala: how to create a generic type that is a subtype of all number classes in scala so that it can include a comparison method

I'm trying to create a generic class with a generic type that is a subclass of Numeric (to make sure I'm dealing with numbers). and I tried " class NuVector[T<:Numeric[T]) " as a def class, and it compiles a fine.

Now I want to add PartiallyOrdered[T] to it. so I did the following:

 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]] } } 

It does not compile. The error I get when compiling:

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

The scala version I'm using is 2.8

Any help is appreciated.

Thanks,
~ Tiger.
I do not know if this is a mistake or its problem with my definition.

+6
generics scala
source share
2 answers

Scala Numeric[T] uses the "Typeclass Pattern" . It makes no sense to say class NuVector[T <: Numeric[T]] . Instead, you want class NuVector[T](implicit n: Numeric[T]) .

+7
source share

even better, use class NuVector[T:Numeric]

This is also called the context boundary and is just syntactic sugar for class NuVector[T](implicit n: Numeric[T])

where n is actually some kind of synthetically generated name that you cannot directly access

+5
source share

All Articles