3

有一个类的构造函数参数列表很长:

case class ClassA(a: Int, b: String, c: Int /*and so on*/)

我需要对它进行模式匹配:

val cls = getClassA
cls match {
  case ClassA(a, _, _, _, _, /* and so on */) => Some(a)
  case ClassA(_, _, c, _, _, /* and so on */) => Some(c)
  case _ => None
}

我需要捕获aor的值c_如果我真的不需要它们,是否可以不指定所有其他参数?

val cls = getClassA
    cls match {
      case ClassA(a, _*) => Some(a)
      case ClassA(_, _, c, _*) => Some(c)
      case _ => None
    }

它给了我错误:wrong number of arguments for pattern ClassA(a, b, /*and so on*/)

4

2 回答 2

7

在案例类中,您需要在匹配时指定整个参数列表。

另一种方法是实现您自己的unapply方法,该方法可以正确处理您传递的任何参数。

于 2013-09-13T15:43:20.050 回答
4

Since companion objects of case classes have unapply method, not unapplySeq, it doesn't work.

If you want to use unapply to check against only one field, you can define something like this:

object ClassAByA {
  def unapply(obj: ClassA) = Some(obj.a)
}

val ClassAByA(x) = ClassA(100, "thousand", 10000.0)
// x is equal 100 now

ClassA(100, "a", 10000.0) match {
  case ClassAByB(str) => str // str is equal "a" now
}

or you can just write:

something match {
  case c: ClassA => c.b
}
于 2013-09-17T14:49:45.167 回答