fadsend fadsend - 1 year ago 51
Scala Question

Compiler error when using pattern matching on list of pairs in scala

I'm learning Scala pattern matching and encountered the following issue:

Suppose i have the list of integers and using pattern matching to match the last element:

val list = 1 :: 2 :: 3 :: Nil

list match {
case xs :+ 3 => println("Matched")
case _ => println("Not matched")
}


In this case it works without problems and "Matched" is printed.

But the issue comes when i use list of pairs instead:

val list = ('a', 1) :: ('b', 2) :: ('c', 3) :: Nil
list match {
case xs :+ ('c', 3) => println("Matched")
case _ => println("Not mathed")
}


When i write this, i get the following error:

<console>:14: error: too many patterns for object :+ offering
(List[(Char, Int)], (Char, Int)): expected 2, found 3
case xs :+ ('c', 3) => println("Matched")
^
<console>:14: error: type mismatch;
found : Char('c')
required: (Char, Int)
case xs :+ ('c', 3) => println("Matched")


Did i miss something here and if there is some correct way to do this?

scala version is 2.11.8.

Thanks

Answer Source

You need to enclose the appended pair with parenthesis. The method :+ accepts one parameter. If you dont have extra parenthesis, two parameters are being assumed.

list match {
     case xs :+ (('c', 3)) => println("Matched")
     case _ => println("Not mathed")
  }