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
vucalur
  • 6,007
  • 3
  • 29
  • 46
  • I'd suggest biting the bullet and writing the underscores, or (even better) trying to break your case classes down into smaller pieces. – Travis Brown Jun 07 '14 at 18:50
  • 2
    This is currently impossible, but there are suggestions to allow matching with named and default parameters (see [here](https://issues.scala-lang.org/browse/SI-5323) and [here](https://issues.scala-lang.org/browse/SI-6524)) that would allow an easy syntax for this. – wingedsubmariner Jun 07 '14 at 18:57
  • Related: http://stackoverflow.com/questions/3474125/how-to-pattern-match-large-scala-case-classes – Florian F May 31 '15 at 21:47

2 Answers2

2

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)
elm
  • 20,117
  • 14
  • 67
  • 113
-1
case o: MyOctet => o.a + o.b
kulikov
  • 1,604
  • 1
  • 10
  • 2
  • 2
    I'm not the downvoter, but this isn't really an answer given the "when using generated extractor" part of the question. – Travis Brown Jun 07 '14 at 17:58
  • Me neither. Code snippet proposed by me is hello-worldish, just to put across the problem, so for that specific use @kulikov's solution is definitely cleaner. However, in case of complex usages, e.g. nested extractors, using an extractor might be the only way to go, hence the question. – vucalur Jun 07 '14 at 18:10
  • 1
    @vucalur: If I had my way matching on type like this would be considered an advanced technique and protected by an import. It's sometimes useful but is generally a code smell and has lots of weird limitations with generics. – Travis Brown Jun 07 '14 at 18:49