简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM