E031: Sequence Wildcard Pattern Position
This error is emitted when the sequence wildcard pattern (_*) is used in a position other than the last element in a pattern sequence.
The sequence wildcard pattern is expected at the end of an argument list. This pattern matches any remaining elements in a sequence.
Example
def example(list: List[Int]): Int = list match
case List(x: _*, second, third) => second
case _ => 0
Error
-- [E031] Syntax Error: example.scala:2:15 -------------------------------------
2 | case List(x: _*, second, third) => second
| ^
| * can be used only for last argument
|-----------------------------------------------------------------------------
| Explanation (enabled by `-explain`)
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| Sequence wildcard pattern is expected at the end of an argument list.
| This pattern matches any remaining elements in a sequence.
| Consider the following example:
|
| def sumOfTheFirstTwo(list: List[Int]): Int = list match {
| | case List(first, second, x*) => first + second
| | case _ => 0
| |}
|
| Calling:
|
| sumOfTheFirstTwo(List(1, 2, 10))
|
| would give 3 as a result
-----------------------------------------------------------------------------
Solution
// Place the sequence wildcard at the end using modern syntax
def example(list: List[Int]): Int = list match
case List(first, second, rest*) => second
case _ => 0
// Alternative: match the exact number of elements you need
def example(list: List[Int]): Int = list match
case first :: second :: _ => second
case _ => 0
In this article