Back to Scala3

E107: Unapply Invalid Number of Arguments

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

3.8.42.0 KB
Original Source

E107: Unapply Invalid Number of Arguments

This error is emitted when a pattern match uses an extractor with the wrong number of argument patterns.

The number of argument patterns in a case clause must match the number of values returned by the extractor's unapply method. When unapply returns a Boolean (indicating match/no-match without extracting values), no argument patterns should be used.


Example

scala
object IsEven:
  def unapply(x: Int): Boolean = x % 2 == 0

def example(n: Int) = n match
  case IsEven(x) => "even"
  case _ => "odd"

Error

scala
-- [E107] Syntax Error: example.scala:5:13 -------------------------------------
5 |  case IsEven(x) => "even"
  |       ^^^^^^^^^
  |       Wrong number of argument patterns for IsEven; expected: ()
  |-----------------------------------------------------------------------------
  | Explanation (enabled by `-explain`)
  |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  | The Unapply method of IsEven was used with incorrect number of arguments.
  | Expected usage would be something like:
  | case IsEven() => ...
  |
  | where subsequent arguments would have following types: ().
   -----------------------------------------------------------------------------

Solution

scala
// Use empty argument list for Boolean-returning unapply
object IsEven:
  def unapply(x: Int): Boolean = x % 2 == 0

def example(n: Int) = n match
  case IsEven() => "even"
  case _ => "odd"
scala
// Or use Option-returning unapply to extract values
object IsEven:
  def unapply(x: Int): Option[Int] =
    if x % 2 == 0 then Some(x) else None

def example(n: Int) = n match
  case IsEven(x) => s"even: $x"
  case _ => "odd"
<!-- 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>