bug icon indicating copy to clipboard operation
bug copied to clipboard

Issue with extractor pattern in Scala 2.13

Open akshayakp97 opened this issue 1 year ago • 2 comments

Reproduction steps

Scala version: 2.13

// Step 1: Define the case class Person
case class Person(name: String, age: Int, id: Int)

// Step 2: Define the companion object with the unapply method
object Person {
  def unapply(person: Person): Option[(String, Int)] = {
    Some((person.name, person.age))
  }
}

// Define an object
val person = Person("Alice", 30, 12345)

// Extract the fields
val canBind = person match {
  case person @ Person(name, age, id) => true
  case _ => false
}

println(s"$canBind")

Problem

The above code works fine in Scala 2.12. However, it doesn't compile with scala 2.13. With scala 2.13, I see error: too many patterns for object Person offering (String, Int): expected 2, found 3.

Discord conversation link

akshayakp97 avatar Jun 13 '24 00:06 akshayakp97

Scala 3 also errors:

-- Error: /Users/luc/code/scala/scala13/sandbox/U.scala:17:25 ------------------
17 |    case person @ Person(name, age, id) => true
   |                         ^
   |this case is unreachable since type (String, Int) is not a subclass of class Tuple3
1 error found

lrytz avatar Jun 13 '24 07:06 lrytz

I see I quoted scripture on chat:

However, instead of a case class, the stable identifier xx denotes an object which has a member method named unapply or unapplySeq that matches the pattern.

It's not clear whether the case class can participate in constructor patterns when the unapply does not match the pattern.

som-snytt avatar Jun 13 '24 08:06 som-snytt