对于以下案例类:
scala> case class Foo[T](name: String) {}
defined class Foo
scala> val foo = Foo[Int]("foo")
foo: Foo[Int] = Foo(foo)
为什么 Scala 会像我认为的那样让我匹配 on Foo[Int]
?不是Int
删了吗?
scala> foo match {
| case _: Foo[Int] => "foo"
| case _ => "bar"
| }
res2: String = foo
但是在包含另一个模式匹配案例时会显示编译时错误?
scala> foo match {
| case _: Foo[String] => "string"
| case _: Foo[Int] => "int"
| case _ => "other"
| }
<console>:12: warning: non-variable type argument String in type pattern Foo[String] is unchecked since it is eliminated by erasure
case _: Foo[String] => "string"
^
<console>:12: error: pattern type is incompatible with expected type;
found : Foo[String]
required: Foo[Int]
case _: Foo[String] => "string"
^