为什么匹配List [Any]不会生成未经检查的类型警告?

时间:2018-01-17 04:57:58

标签: scala type-erasure scala-2.12

任何人都知道为什么这些会生成未经检查的警告......

def anyMap(a: Any): Unit = a match {
  case _: Map[Any, Any] => 
}
//warning: non-variable type argument Any in type pattern scala.collection.immutable.Map[Any,Any] (the underlying of Map[Any,Any]) is unchecked since it is eliminated by erasure

def intList(a: Any): Unit = a match {
  case _: List[Int] =>
}
//warning: non-variable type argument Int in type pattern List[Int] (the underlying of List[Int]) is unchecked since it is eliminated by erasure

......但这不是吗?

def anyList(a: Any): Unit = a match {
  case _: List[Any] =>
}
//[crickets]

大多只是好奇。感谢

1 个答案:

答案 0 :(得分:1)

Scala可以通过检查它是List[Any]来验证某些内容是否满足List。这是因为the list type在其第一个参数中是协变的,所以即使你传递了List[Int]List[Double],那些仍然是子类List[Any],所以所有的编译器必须做的是检查List,它可以在运行时执行。类型擦除不会影响其执行此操作的能力。

检查某些内容是否为List[Int]需要知道元素的实际类型, 在运行时被删除,而Scala不能使用{{{ 1}}因为the map type在其第一个参数中是不变的。因此,虽然Map[Any, Any]Map[Any, Int]的子类,但Map[Any, Any]却不是。因此,Scala必须能够检查第一个参数的类型,它在运行时无法完成。

有关方差的更多信息,请in the docs

相关问题