为什么scala编译器说这种类型用于非特殊化的位置?

时间:2012-12-13 19:12:31

标签: scala generics compiler-construction compiler-warnings jvm-languages

我在package对象中有这个方法:

def extractLoop[@specialized T](x: Map[T, T]) = {
    val whatever = x.head
    val stop = whatever._1
    def iteration(
            acc: Seq[T] = Seq(whatever._1, whatever._2),
            last: T = whatever._2): Seq[T] = {
        val next = x(last)
        if (next == stop) acc
        else iteration(acc :+ next, next)
    }
    iteration()
}

但我还不明白,为什么编译器(我有2.9.2版本)说type T is unused or used in non-specializable positions.

1 个答案:

答案 0 :(得分:5)

我认为原因很简单,你使用的是Map[T, T]并非专业。

一些例子:

scala> class MyMap[A,B]
defined class MyMap
scala> def extractLoop[@specialized T](x: MyMap[T, T]) = {
     |   sys.error("TODO")
     | }
<console>:8: warning: type T is unused or used in non-specializable positions.
       def extractLoop[@specialized T](x: MyMap[T, T]) = {
           ^
extractLoop: [T](x: MyMap[T,T])Nothing

但是如果你将MyMap专门用于它的两个类型参数,则没有警告:

scala> class MyMap[@specialized A,@specialized B]
defined class MyMap
scala> def extractLoop[@specialized T](x: MyMap[T, T]) = {
     |   sys.error("TODO")
     | }
extractLoop: [T](x: MyMap[T,T])Nothing