Sar*_*sch 3 compiler-construction generics scala jvm-languages compiler-warnings
我在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()
}
Run Code Online (Sandbox Code Playgroud)
但我还不明白,为什么编译器(我有版本2.9.2)说type T is unused or used in non-specializable positions.?
我相信原因很简单,你使用的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
Run Code Online (Sandbox Code Playgroud)
但如果你专门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
Run Code Online (Sandbox Code Playgroud)