DevZer0 DevZer0 - 2 months ago 19
Scala Question

correct use of @specialized in Scala

I am trying to implement a method that can accept a

Seq
of
Int
and
Double
. I heard that this can be done using
Numeric
however I read about an annotation called
@specialized
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
T
is a
String
.

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

Answer

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.)