1

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

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]

大多只是好奇。谢谢

4

1 回答 1

1

List[Any]Scala 可以简单地通过检查某事物的类型是否为List. 这是因为列表类型在它的第一个参数中是协变的,所以即使你传递它 aList[Int]或 a List[Double],它们仍然是子类 are List[Any],所以编译器所要做的就是 check List,它可以在运行时执行。类型擦除不会影响其执行此操作的能力。

检查某个东西是否是 aList[Int]需要知道元素的实际类型,这些元素在运行时会删除,而 Scala 无法使用相同的技巧,Map[Any, Any]因为映射类型在其第一个参数中是不变的。所以 whileMap[Any, Int]是 的子类Map[Any, Any]Map[Int, Any]不是。因此,Scala 必须能够检查第一个参数的类型,而这在运行时无法做到。

更多关于方差的信息可以在 docs中找到。

于 2018-01-17T05:10:59.607 回答