Back to Scala3

E031: Sequence Wildcard Pattern Position

docs/_docs/reference/error-codes/E031.md

3.8.42.0 KB
Original Source

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

scala
def example(list: List[Int]): Int = list match
  case List(x: _*, second, third) => second
  case _ => 0

Error

scala
-- [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

scala
// 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
scala
// Alternative: match the exact number of elements you need
def example(list: List[Int]): Int = list match
  case first :: second :: _ => second
  case _ => 0
<!-- SOURCE-ONLY: Remove the notice below once this page has been manually updated. --> <aside class="warning"> This reference page was created with LLM assistance - the description of the error code may not be accurate or cover all possible scenarios. </aside>