12

given following code:

abstract class MyTuple

... 

case class MySeptet(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int) extends MyTuple

case class MyOctet(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, h: Int) extends MyTuple

...

When using generated extractor, is it possible to skip remaining parameters, supposing they're unused ?

e.g. I don't want to write plenty of underscores in the following code snippet:

case MyOctet(a, b, _, _, _, _, _, _) => ... // uses only a and b
4

2 回答 2

2

一种为元组类提供提取器的简单方法,实际上依赖于Array提取器,因此绕过了原始问题。

abstract class MyTuple (order: Int)
case class MySeptet(coord: Array[Int]) extends MyTuple(7)
case class MyOctet(coord: Array[Int]) extends MyTuple(8)

等等

val o = MyOctet( (1 to 8).toArray )

我们可以像这样提取八位字节中的前两个元素,

o match {
  case MyOctet( Array(a,b,_*) ) => a+b
  case _ => 0
}
res: Int = 3

请注意,这并没有解决在上面定义的案例类中跳过剩余参数的问题。

还要注意这种方法的一个弱点,如下所示,

scala> val Array(a,b) = Array(1)
scala.MatchError: [I@16a75c0 (of class [I)
于 2014-06-08T06:34:30.713 回答
-1
case o: MyOctet => o.a + o.b
于 2014-06-07T17:36:58.640 回答