Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala extractors - skip unused parameters

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
like image 818
vucalur Avatar asked Jun 07 '14 16:06

vucalur


1 Answers

A simple approach to providing extractors for tupled classes that relies in fact in Array extractors, hence bypassing the original problem.

Let

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

and so for

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

we can extract the first two elements in an octet like this,

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

Note this does not address the problem of skipping remaining parameters in the case classes defined above.

Also note a weakness of this approach, illustrated as follows,

scala> val Array(a,b) = Array(1)
scala.MatchError: [I@16a75c0 (of class [I)
like image 138
elm Avatar answered Nov 16 '22 14:11

elm