tags:

views:

534

answers:

2

Hi, I am trying to create a generic class with generic type being subclass of Numeric (to ensure that I am dealing with numbers.) and I tried "class NuVector[T<:Numeric[T])" as class def and it compiling 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 is not compiling. The error I am getting while compiling is:

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

Scala version I am using is 2.8

Any help is greatly appreciated.

Thanks,
~Tiger.
I don't know whether it is a bug or its a problem with my definition.

+5  A: 

Scala's Numeric[T] uses the "Typeclass Pattern". It doesn't really make sense to say class NuVector[T <: Numeric[T]]. What you want, instead, is class NuVector[T](implicit n: Numeric[T]).

Jorge Ortiz
And the shortcut for this is the "context bound" introduced in Scala 2.8: `class NuVector[T : Numeric]`. Where this `T` is in scope, the evidence parameter may be acquired using `val num = implicitly[Numeric[T]]`.
Randall Schulz
A: 

even better, use class NuVector[T:Numeric]

This is also known as a context bound, and is just syntactic sugar for class NuVector[T](implicit n: Numeric[T])

where n is actually some synthetically-generated name that you can't access directly

Kevin Wright