gpt4 book ai didi

scala - 在 Scala 中匹配案例类的子类

转载 作者:行者123 更新时间:2023-12-03 10:09:12 25 4
gpt4 key购买 nike

为什么这无法编译(或工作?):

  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

我还没有找到指向导致原始问题的特定错误的指针,但忽略有关案例类继承的警告,后果自负。

关于scala - 在 Scala 中匹配案例类的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2060728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com