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

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

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

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:

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:

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