我可以在案例类的匹配中使用抽象类型吗?

时间:2013-03-10 03:16:29

标签: scala pattern-matching case-class

或者换句话说: 我是否可以通过匹配验证元组中的元素是否属于同一个案例类,尽管他们的字段(参数)中的值不同? 是否有相当于案例[T] 的内容?

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.")
    }
}

我希望我不必这样做:

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.")
    }
}

相关: matching

2 个答案:

答案 0 :(得分:2)

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

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

我不知道任何构造符合您描述的方式,例如case[T]

答案 1 :(得分:0)

这是一个解决方案,我想 - 如果它真的只是关于类:

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)
}

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

示例测试代码:

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))
}

打印:

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