关于scala:我可以在案例类匹配中使用抽象类型吗?

Can I use abstract types in matching of case classes?

或者,换句话说:
我可以通过匹配验证元组中的元素是否具有相同的case类,尽管它们的字段(参数)中的值不同?
是否有与下面的case [T]等效的东西?

1
2
3
4
5
6
7
8
9
10
11
12
sealed abstract class RootClass
case class ChildClassX(valuex: Boolean) extends RootClass
case class ChildClassY(valuey: Boolean) extends RootClass
// and other case classes here...

object Foo {
def compare(a: RootClass, b: RootClass) = {
    (a, b) match {
       case[T] (T(a), T(b)) => a == b
       case _ => throw Exception("a and b should be of same child classes.")
    }
}

我希望我不必做:

1
2
3
4
5
6
7
object Foo {
def compare(a: RootClass, b: RootClass) = {
    (a, b) match {
       case (ChildClassX(a), ChildClassX(b)) | (ChildClassY(a), ChildClassY(b)) | (ChildClassZ(a), ChildClassZ(b)) | etc. => a == b
       case _ => throw Exception("a and b should be of same child classes.")
    }
}

相关:
匹配


我能想到的最合理的解决方案是简单地比较两个项目的类。

1
2
3
4
(a, b) match {
  case (x,y) if x.getClass == y.getClass =>"matching classes"
  case _ =>"no match"
}

我不知道有什么结构可以像您描述的那样工作,例如case[T]


我想这将是一个解决方案-如果它确实仅与类有关:

1
2
3
4
5
6
object Foo {
  def compare[A,B](a: A, b: B) =
    if (a.getClass.getSuperclass != b.getClass.getSuperclass)
      throw new MatchError("a and b should be of same child classes.")
    else (a.getClass == b.getClass)
}

不涉及匹配...也许有人有一个更优雅的解决方案?但这可能是最短的...

测试代码示例:

1
2
3
4
5
6
7
8
object ObjCmp extends App {
  case object X
  val p: Product = ChildClassX(true)
  println(Foo.compare(ChildClassX(true), ChildClassX(false)))
  println(Foo.compare(ChildClassX(true), ChildClassY(false)))
  println(Foo.compare(ChildClassX(true), p))
  println(Foo.compare(ChildClassX(true), X))
}

打印:

1
2
3
4
true
false
true
Exception in thread"main" scala.MatchError: a and b should be of same child classes.