DevZer0 DevZer0 - 1 year ago 91
Scala Question

correct use of @specialized in Scala

I am trying to implement a method that can accept a

. I heard that this can be done using
however I read about an annotation called
in a Scala book.

So I tried implementing a method as follows

def getMedian[@specialized(Int, Double) T](s:Seq[T]):T = {
s.sorted match {
case y:Seq[T] if (y.length % 2 == 0) => y(0) + y(1) / 2

However Scala doesn't recognise the
operation because type hinting seems to think
is a

Note: I have simplified the equation for readability. It no longer represents a median calculation.

Answer Source

You simply can't use @specialized for this. Your code still has to compile if @specialized is removed; the annotation tells the compiler to also generate specialized versions for T = Int and T = Double. So you still need Numeric.

(So far as I understand, in this case @specialized is basically useless because Seq and Numeric aren't specialized.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download