Skip to content

Pattern matching on unchecked generic types (with isInstanceOf guard) does not work correctly #14705

Closed
@liosedhel

Description

@liosedhel

Compiler version

scala 3.1.1

Minimized code

trait Fruit
case class Apple() extends Fruit
case class Orange() extends Fruit

case class Box[C](fruit: C) extends Fruit

val apple = Box(fruit = Apple())
val orange = Box(fruit = Orange())


val result = List(apple, orange).map {
  case appleBox: Box[Apple] @unchecked if appleBox.fruit.isInstanceOf[Apple] => //contains apple
    "apple"
  case _ => 
    "orange"
}

assert(result == List("apple", "orange"))

Output

result == List("apple", "apple")

Expectation

Only Box with Apple inside should be matched as "apple". It works for 2.13.x scala version. It can be workarounded with

case appleBox: Box[_] @unchecked if appleBox.fruit.isInstanceOf[Apple] =>
  val a = appleBox.asInstanceOf[Box[Apple]]

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions