Core_Dumped
Core_Dumped

Reputation: 4699

Scala: Pattern matching in tuples

I know the fact that tuples are immutable in Scala. Hence, I am using pattern matching to change my tuples. I have a 2-tuple having two 3-tuple elements, each element being a sequence. My problem is: 'If the first element of the first tuple is an empty sequence, send some default value.' My code looks something like this:

val (fooTuple, barTuple) = 
{
// function that returns a 2-tuple with elements that are 3-tuples
((a, b, c), (d, e, f)) //Each of these is a sequence
} match {
case ((Seq(), x, y), z) => ((Seq("default"), x, y), z)
}

It throws a MatchError printing the value of ((a, b, c), (d, e, f)) What am I doing wrong?

Upvotes: 0

Views: 456

Answers (1)

4lex1v
4lex1v

Reputation: 21547

It failed for cases when your first elements is not empty, you can fix this by handling other cases:

val (fooTuple, barTuple) = 
{
// function that returns a 2-tuple with elements that are 3-tuples
((a, b, c), (d, e, f)) //Each of these is a sequence
} match {
  case ((Seq(), x, y), z) => ((Seq("default"), x, y), z)
  case other => other
}

Where all other cases would be handled by case other => other

Upvotes: 3

Related Questions