Skip to content

Missing variance check on private members #18588

Closed
@alexandru

Description

@alexandru

Compiler version

From 3.0.0 to 3.3.1.

Minimized code

This code compiles fine, but fails at runtime with a ClassCastException. Note that it contains no @uncheckedVariance annotations or forced down-casting:

class Box[+A](value: A) {
  private var cached: A = value
  def get: A = cached

  def put[AA >: A](value: AA): Unit = {
    val box: Box[AA] = this
    box.cached = value
  }
}

trait Animal
object Dog extends Animal
object Cat extends Animal

val dogBox: Box[Dog.type] = new Box(Dog)
dogBox.put(Cat)
val dog: Dog.type = dogBox.get

Note: I actually noticed this in the lampepfl/gears repository (see sample).

Expectation

The compiler should issue an error like:

Covariant type A occurs in contravariant position in type A of value cached

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:typeritype:bugitype:soundnessSoundness bug (it lets us compile code that crashes at runtime with a ClassCastException)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions