加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Scala中匹配案例类的子类

发布时间:2020-12-16 10:01:21 所属栏目:安全 来源:网络整理
导读:为什么这不能编译(或工作?): case class A(x: Int) class B extends A(5) (new B) match { case A(_) = println("found A") case _ = println("something else happened?") } 编译器错误是: constructor cannot be instantiated to expected type; found
为什么这不能编译(或工作?):

case class A(x: Int)
  class B extends A(5)

  (new B) match {
    case A(_) => println("found A")
    case _ => println("something else happened?")
  }

编译器错误是:

constructor cannot be instantiated to expected type;  found   : blevins.example.App.A  required: blevins.example.App.B

请注意,这将按预期编译并运行:

(new B) match {
    case a: A => println("found A")
    case _ => println("something else happened?")
  }

附录

仅供参考,这编译并运行良好:

class A(val x: Int)
  object A {
    def unapply(a: A) = Some(a.x)
  }
  class B extends A(5)

  (new B) match {
    case A(i) => println("found A")
    case _ => println("something else happened?")
  }

解决方法

这有效,至少在2.8:

scala>   case class A(x: Int)                           
defined class A

scala>   class B extends A(5)                           
defined class B

scala>   (new B: A) match {                             
     |     case A(_) => println("found A")              
     |     case _ => println("something else happened?")
     |   }                                              
found A

我没有找到导致原始问题的特定错误的指针,但忽略了关于案例类继承的警告,这是你自己的危险.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读