scala - 使用通用案例类了解删除

标签 scala erasure

对于以下案例类别:

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/

相关文章:

scala - 在 Delite 中编译我的第一个 DSL

java - instanceof List 和 instanceof List<?> 的区别

java - 区别只是 List 和 List<Object> 和 List<?>

Java 删除 -> 编译时类型对齐 - 或 Java 库/框架代码转换为应用程序逻辑

scala - 如何获得当前工作中使用的核心数?

Scala获取ArrayBuffer的第一个满足条件的元素

java - 自动化性能测试框架

scala - 与 Option.isEmpty 和 Option.get 相比,使用 Option.map 有什么优势?

java - 删除类型和桥接方法澄清