scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
232 stars 21 forks source link

Issue with extractor pattern in Scala 2.13 #13008

Open akshayakp97 opened 3 months ago

akshayakp97 commented 3 months ago

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

lrytz commented 3 months ago

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
som-snytt commented 3 months ago

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.