Skip to content

ClassCastException when using named pattern with Name-based Match #22900

Closed
@SrTobi

Description

@SrTobi

Compiler version

3.7.1-RC1-bin-20250328-d519790-NIGHTLY

Minimized code

object NameBaseExtractor {
  def unapply(x: Int): Some[(someName: Int)] = Some((someName = x + 3))
}

@main
def run = {
  val NameBaseExtractor(someName = x) = 3
  println(x)
}

Output

Exception in thread "main" java.lang.ClassCastException: class scala.Tuple1 cannot be cast to class java.lang.Integer (scala.Tuple1 is in unnamed module of loader 'app'; java.lang.Integer is in module java.base of loader 'bootstrap')
	at scala.runtime.BoxesRunTime.unboxToInt(BoxesRunTime.java:99)
	at org.test.Test$package$.run(Test.scala:11)
	at org.test.run.main(Test.scala:9)

Note that it also prints the warning:

pattern's type (x : Int) is more specialized than the right hand side expression's type Int

If the narrowing is intentional, this can be communicated by adding `: @unchecked` after the expression,
which may result in a MatchError at runtime.
This patch can be rewritten automatically under -rewrite -source 3.2-migration.
  val NameBaseExtractor(someName = x) = 3

But I think this is just #22899

Expectation

Prints 6

Metadata

Metadata

Assignees

Labels

area:named-tuplesIssues tied to the named tuples feature.area:pattern-matchingitype:bugitype:soundnessSoundness bug (it lets us compile code that crashes at runtime with a ClassCastException)

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions