user445107
user445107

Reputation:

Can I use abstract types in matching of case classes?

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

Upvotes: 1

Views: 114

Answers (2)

Dylan
Dylan

Reputation: 13924

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].

Upvotes: 2

michael_s
michael_s

Reputation: 2575

This would be a solution, I guess - if it's really only about the classes:

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

No matching involved... Maybe someone has a more elegant solution? But this is maybe the shortest...

Example test code:

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

prints:

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

Upvotes: 0

Related Questions