You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 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.
-- 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
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.
SethTisue
changed the title
Issue with extractor pattern in Scala 2.13
Issue with extractor pattern (unapply override with different parity)
Nov 6, 2024
SethTisue
changed the title
Issue with extractor pattern (unapply override with different parity)
Issue with extractor pattern (unapply override with different arity)
Nov 6, 2024
Reproduction steps
Scala version: 2.13
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
The text was updated successfully, but these errors were encountered: