I want to create a covariant class which is mutable, so I need to add a lower type bound to the setter method. But I also want the setter method to set a field, so I guess the field needs to have the same type bound?
class Thing[+F](initialValue: F) {
private[this] var secondValue: Option[G >: F] = None
def setSecondValue[G >: F](v: G) = {
this.secondValue = Some(v)
}
}
The method compiles fine. But the field called secondValue doesn’t compile at all, with the error message:
Multiple markers at this line
- ']' expected but '>:' found.
- not found: type G
What do I need to do?
You need the
forSomeconstruct, which introducesGas existential type:In your original code for
secondValue,Ghas been pulled out of thin air, i.e., it hasn’t been introduced properly. In case ofsetSecondValuethe user (or the compiler) bindsGat call site, but for a field that’s not an option (especially, since yours is private). Read more aboutforSomeand existential types in Scala here, here or here.