Unexpected "type mismatch"

Given the following code:

class ChipsPane[A <: ChipsPane.ChipValue] {
  def add(a: A): Unit = ???

  val chip = new ChipsPane.ChipValue {
    override def label = "???"
  }

  add(chip)
}

object ChipsPane {
  trait ChipValue {
    def label: String
  }
}

For this code I get the following compiler error:

type mismatch;
found   : ChipsPane.ChipValue
required: A
add(chip)

But if I replace add(chip) with add(chip.asInstanceOf[A]), everything works fine.

Can anyone tell me what’s wrong with my code?

There’s some subtype A of ChipValue (which may be ChipsValue itself, but could be a real subtype) which is provided upon instantiation of ChipsPane. Now inside ChipsPane you assume that A =:= ChipValue. Consider MyChipValue extends ChipValue and new ChipsPane[MyChipValue], though - the assumption doesn’t hold.

2 Likes

I am pretty sure that I don’t understand what you try to explain me. (My fault).

I expected that A must be any subtype of ChipValue and chip is clearly a subtype of ChipValue, isn’t it?

A can be any subtype of ChipValue (or ChipValue itself), but for a given instance of ChipsPane it is a specific subtype of ChipValue (or ChipValue itself) that is provided upon instantiation. For new ChipsPane[MyChipValue], A is bound to MyChipValue, and chip clearly is not of type MyChipValue.

2 Likes