1

または、言い換えると、フィールド (引数) の値が異なるにもかかわらず、タプル内の要素が同じケース クラスであるかどうかを照合して検証できますか? 以下のケース[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

私が考えることができる最も合理的な解決策は、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 に答える