对于以下案例类别:
scala> case class Foo[T](name: String) {}
defined class Foo
scala> val foo = Foo[Int]("foo")
foo: Foo[Int] = Foo(foo)
为什么 Scala 让我(正如我认为的那样)匹配 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"
^
最佳答案
class SuperFoo;
case class Foo[T](name: String) extends SuperFoo {}
val foo: SuperFoo = Foo[Int]("foo")
foo match {
case _: Foo[String] => "foo"
case _ => "bar"
} //> res0: String = foo + warning
在您的情况下,编译器知道 foo
的确切类型。
关于scala - 使用通用案例类了解删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913669/