相关疑难解决方法(0)

如何在Scala上绕过类型擦除?或者,为什么我不能获得我的集合的类型参数?

Scala生活中的一个可悲事实是,如果你实例化一个List [Int],你可以验证你的实例是一个List,你可以验证它的任何单个元素是一个Int,但不是它是一个List [ Int],可以很容易地验证:

scala> List(1,2,3) match {
     | case l : List[String] => println("A list of strings?!")
     | case _ => println("Ok")
     | }
warning: there were unchecked warnings; re-run with -unchecked for details
A list of strings?!
Run Code Online (Sandbox Code Playgroud)

-unchecked选项将责任直接归咎于类型擦除:

scala>  List(1,2,3) match {
     |  case l : List[String] => println("A list of strings?!")
     |  case _ => println("Ok")
     |  }
<console>:6: warning: non variable type-argument String in type pattern is unchecked since it is eliminated by erasure
        case l …
Run Code Online (Sandbox Code Playgroud)

scala type-erasure

366
推荐指数
7
解决办法
7万
查看次数

为什么将成员变量的擦除警告声明为元组?

看看这个Scala类:

class Example {
  val (x, y): (Int, Int) = (1, 2)
}
Run Code Online (Sandbox Code Playgroud)

编译这会导致警告:

Example.scala:2: warning: non variable type-argument Int in type pattern
               (Int, Int) is unchecked since it is eliminated by erasure
    val (x, y): (Int, Int) = (1, 2)
                ^
Run Code Online (Sandbox Code Playgroud)

删除显式类型注释会消除此警告:

class Example {
  val (x, y) = (1, 2)
}
Run Code Online (Sandbox Code Playgroud)

为什么我会收到警告,为什么删除显式类型注释会删除它?据我所知,没有任何真正的变化,x并且y仍然是Int没有类型注释的类型.

scala compiler-warnings type-erasure

9
推荐指数
2
解决办法
481
查看次数

标签 统计

scala ×2

type-erasure ×2

compiler-warnings ×1