bug
bug copied to clipboard
Potential ClassCastException when pattern matching case class within generic trait
Using Scala 2.12.6, the following code crashes with a ClassCastException:
trait Outer[T] {
object Group {
case class C1(x: T)
}
}
object IntOuter extends Outer[Int]
object StringOuter extends Outer[String]
val c1: Any = IntOuter.Group.C1(123)
c1 match {
case StringOuter.Group.C1(v) => println(v)
case _ => println("Not a string")
}
// Results in error: Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
The exception occurs when trying to print the matched value v.
By removing the Group wrapper object, the code works as expected. It seems that the extra wrapper object makes the compiler skip checking the $outer reference that is present in the inner case class.
This bug is related to #9639 and Test1 in #6583. #9639 is still reported as open, but it seems to be fixed in Scala 2.12.6.
Just tested this case in newer Scala versions. It also fails for 2.13.0-M5. In Dotty 0.9.0-RC, it works OK.
Another observation: By introducing a trait, the code works as expected:
trait Outer[T] {
trait Group {
case class C1(x: T)
}
object Group extends Group
}