scala - 为什么 scala 编译器说这种类型用在非特化位置?

标签 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.?

最佳答案

我认为原因很简单,您使用的是非专用的 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

关于scala - 为什么 scala 编译器说这种类型用在非特化位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866758/

相关文章:

scala - 将 Spark 流数据写入并附加到 HDFS 中的文本文件

compiler-construction - 是否有Lisp native 代码编译器?

C# Generics - 根据对象类型找到正确的具体类

c# - 如何交叉两个不同的 IEnumerable 集合

java - 接口(interface)泛型和 instanceof

c - 哪些 C99 功能被认为是有害的或不受支持的

c - 编译 Neko VM OS X 时出错

mysql - 在 Scala 中,当进行巧妙的 sortBy 时,如何让它进行区分大小写的排序

scala - 对 Apache-Spark 数据帧中的距离求和

scala - 使用 IntelliJ 处理多个相互依赖的 SBT 项目