1

Consider

val b = ParArray("a","b","c")

However, on pattern matching b for instance as follows,

b match {
  case ParArray(_,"b",_) => 2
  case _ => -1
}


<console>:11: error: object ParArray is not a case class, 
                     nor does it have an unapply/unapplySeq member
              case ParArray(_,"b",_) => 2

Thus how to pattern match ParArray ?

Thanks in Advance.

elm
  • 20,117
  • 14
  • 67
  • 113
  • 1
    You can not pattern-match like that, because there is no `unapply` defined on ParArray. A workaround could be to use `b.toList match { case List(_, "b", _) => ...}` – Kigyo May 22 '14 at 07:14

1 Answers1

3

ParArray is a parallel structure. Its main usecase is to operate on the elements concurrently (see docs). That's done (roughly speaking) by concurrently applying operations on arbitratry segments of the ParArray.

For the sake of a counter example, imagine that you could unapply on ParArray. How would the match look like:

Given val b = ParArray("a","b","c","d")

b match {
  case ParArray(_,"b",_) => 2
  case _ => -1
}

Could be arbitrarily converted into:
//Parallel split & join:
"a","b" match {
  case ParArray(_,"b",_) => 2
  case _ => -1
}

"c","d" match {
  case ParArray(_,"b",_) => 2
  case _ => -1
}

Which of course, doesn't make sense. For the specific case on your question, you could use direct addressing:

if (b.size == 3 && b(1)=="b") 2 else -1

In a more generic sense, a good way of reasoning is thinking of how your operation could be applied to all elements at the same time.

If you need to match on structure, you could obtain an array with the parArray.toArray method. You should also question why is a ParArray being used.

maasg
  • 37,100
  • 11
  • 88
  • 115