Or, in other words: Can I verify with matching if elements in a tuple are of the same case class, despite having different values in theirs fields (arguments)? Is there something equivalent to the case[T] below?
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.")
}
}
I hope I dont have to do:
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.")
}
}
Related: matching
The most reasonable solution that I can think of is to simply compare the two items' classes.
(a, b) match {
case (x,y) if x.getClass == y.getClass => "matching classes"
case _ => "no match"
}
I am not aware of any construct that works the way you describe, like case[T]
.