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