Closed
Description
Compiler version
Scala 3.3.1
Minimized code
abstract class Animal { def name: String }
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal
class Wrapper[+T](private var element: T)
object Wrapper {
def main(args: Array[String]): Unit = {
val dog: Wrapper[Dog] = new Wrapper(Dog("Rex"))
val animal: Wrapper[Animal] = dog
animal.element = Cat("Kitty")
println(dog.element.name)
}
}
Output
The code compiles, but when you run the program it crashes with error
Exception in thread "main" java.lang.ClassCastException: class Cat cannot be cast to class Dog (Cat and Dog are in unnamed module of loader 'app')
at Wrapper$.main(Animal.scala:12)
at Wrapper.main(Animal.scala)
Expectation
The code compiles in Scala 3 but didn't compile in 2.13.
It should produce error
Covariant type T occurs in contravariant position in type T of value element
The compiler shouldn't produce the error only when the visibility is private[this]
.
It looks like there is a typo somewhere in the compiler which checks for private
, not private[this]
Related issue in The Scala Plugin, which actually shows the error:
https://youtrack.jetbrains.com/issue/SCL-21676
