1

或者,换句话说:我可以通过匹配来验证元组中的元素是否属于同一个案例类,尽管它们的字段(参数)中有不同的值?有没有与下面的case[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.")
    }
}

相关: 匹配

4

2 回答 2

2

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

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

我不知道有任何结构可以按照您描述的方式工作,例如case[T].

于 2013-03-10T05:44:09.133 回答
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. 
于 2013-03-10T05:07:55.280 回答