为什么scala编译器说这个类型用在不可特化的位置?

问题描述 投票:0回答:1

我在

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.

scala generics compiler-warnings
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.