Back to Scala3

E215: Named Pattern Not Applicable

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

3.8.42.0 KB
Original Source

E215: Named Pattern Not Applicable

This error is emitted when using named patterns in pattern matching on a type that is not a named tuple or case class.

Named patterns allow you to match elements by name (like name = n) rather than by position. However, this feature is only available for named tuples and case classes, which have known field names that the compiler can use for pattern matching.


Example

scala
class MyClass(val name: String, val age: Int)

object MyExtractor:
  def unapply(x: MyClass): Some[(String, Int)] = Some((x.name, x.age))

def example(obj: MyClass) = obj match
  case MyExtractor(name = n, age = a) => println(s"$n is $a years old")

Error

scala
-- [E215] Pattern Match Error: example.scala:7:18 ------------------------------
7 |  case MyExtractor(name = n, age = a) => println(s"$n is $a years old")
  |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |Named patterns cannot be used with (String, Int), because it is not a named tuple or case class

Solution

Use positional pattern matching instead:

scala
class MyClass(val name: String, val age: Int)

object MyExtractor:
  def unapply(x: MyClass): Some[(String, Int)] = Some((x.name, x.age))

def example(obj: MyClass) = obj match
  case MyExtractor(n, a) => println(s"$n is $a years old")

Or use a case class which supports named patterns:

scala
case class Person(name: String, age: Int)

def example(person: Person) = person match
  case Person(name = n, age = a) => println(s"$n is $a years old")

Named tuples also support named patterns:

scala
def example(data: (name: String, age: Int)) = data match
  case (name = n, age = a) => println(s"$n is $a years old")
<!-- 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>