I have the following code that recursively works with every item in a List
def doMatch(list: List[Int]): Unit = list match { case last :: Nil => println("Final element.") case head :: tail => println("Recursing..."); doMatch(tail) }
Now, ignoring that this function is available through filter () and foreach (), this works just fine. However, if I try to change it to accept any Seq [Int], I run into problems:
- Seq does not have ::, but it has + :, which, as I understand it, is basically the same. If I try to match +: tail on the head, however, the compiler complains about the error: not found: value +: '
- Nil is specific to List, and I'm not sure what to replace it with. I am going to try Seq () if I ever get past the previous problem.
This is how I think the code should look, except that it does not work:
def doMatch(seq: Seq[Int]): Unit = seq match { case last +: Seq() => println("Final element.") case head +: tail => println("Recursing..."); doMatch(tail) }
Edit: so many good answers! I accept agilesteel's answer as it was the first to note that :: is not an operator in my example, but a case class and therefore a difference.
collections scala pattern-matching
Zecrates Jul 24 2018-11-21T00: 00Z
source share