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类:
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
没有类型注释的类型.