sid*_*r09 5 scala type-inference pattern-matching type-erasure
有人可以解释为什么以下代码编译?
Option("foo") match {
case x: List[String] => println("A")
case _ => println("B")
}
Run Code Online (Sandbox Code Playgroud)
这给了我关于类型擦除的(预期)警告,但它仍然编译.我希望这会抛出一个类型错误,就像我匹配"foo"
而不是Option("foo")
.
谢谢!
我假设编译器将 和 视为Option
和List
,Product
这就是它编译的原因。正如您所说,有关类型擦除的警告是预期的。这是使用另一个产品的示例:
scala> Option("foo") match {
| case x: Tuple2[String,String] => println("TUPLE")
| case x: List[String] => println("LIST")
| case _ => println("OTHER")
| }
<console>:9: warning: non variable type-argument String in type pattern (String, String) is unchecked since it is eliminated by erasure
case x: Tuple2[String,String] => println("TUPLE")
^
<console>:10: warning: non variable type-argument String in type pattern List[String] is unchecked since it is eliminated by erasure
case x: List[String] => println("LIST")
^
Run Code Online (Sandbox Code Playgroud)
更新 w/r/t 案例类(因为下面的评论):
scala> case class Foo(bar: Int)
defined class Foo
scala> val y: Product = Foo(123)
y: Product = Foo(123)
Run Code Online (Sandbox Code Playgroud)