7

ライブラリ クラスのケースunapplyがあり、メソッドをオーバーライドして、それに対してパターン マッチングを行うために渡す必要があるパラメータの数を減らしたいと考えています。私はこれをします:

object ws1 {
  // a library class
  case class MyClass(a: Int, b: String, c: String, d: Double /* and many more ones*/)

  // my object I created to override unapply of class MyClass
  object MyClass {
    def unapply(x: Int) = Some(x)
  }

  val a = new MyClass(1, "2", "3", 55.0 /* and many more ones*/)
  a match {
    case MyClass(x /*only the first one is vital*/) => x  // java.io.Serializable = (1,2,3,55.0)
    case _ => "no"
  }
}

しかし、私はそれを返したい1. これの何が問題なのですか?

4

2 に答える 2

8
case class MyClass(a: Int, b: String, c: String, d: Double /* and many more ones*/)
object MyClassA {
   def unapply(x: MyClass) = Some(x.a)
}

val a = new MyClass(1, "2", "3", 55.0 /* and many more ones*/)

a match {
    case MyClassA(2) => ??? // does not match
    case MyClassA(1) => a   // matches
    case _ => ??? 
}

オブジェクトでカスタムunapplyメソッドを定義することはできません。これは、パラメーターを受け取る必要があり、そのようなメソッドが既に 1 つ (ケース クラス用に自動的に生成されたもの) あるためです。したがって、別のオブジェクトで定義する必要があります (この場合)。MyClassMyClassMyClassA

Scala でのパターン マッチングは、オブジェクトを取得し、パターンで指定された値と一致する値になるまで、いくつかのunapplyandメソッドをオブジェクトに適用します。の場合に一致します。unapplySeqSome
MyClassA(1)aMyClassA.unapply(a) == Some(1)

注: と書いcase m @ MyClassA(1) =>た場合、m変数の型は になりますMyClass

編集:

a match {
    case MyClassA(x) => x  // x is an Int, equal to a.a
    case _ => ??? 
}
于 2013-09-17T12:38:02.443 に答える