When an F
type accepts a type parameter of A
, we can add a+
or-
sign in front of the parameter declaration to indicate thevarianceofF
on A
:
We are now going to explore this variance concept with an example. Let's start with a simple class hierarchy, as shown in the following code:
trait Animal case class Cat(name: String) extends Animal case class Dog(name: String) extends Animal
With this hierarchy, I can declare a variable of an Animal
type and assign it to an instance of aCat
orDog
type. The following code will compile:
val animal1: Animal = Cat("Max") val animal2: Animal = Dog("Dolly") implicitly[Dog <:< Animal]
More generally, the assignment val a: A = b: B
compiles...