September 2018
Intermediate to advanced
398 pages
9h 43m
English
Most collection types in the SDK are covariant. For instance, if you open the Vector class, you will see the following:
final class Vector[+A] (...)
This allows us to assign Vector[B] to a variable of Vector[A] if B <:<A type, as shown in the following code:
val cats: Vector[Cat] = Vector(Cat("Max"))val animals: Vector[Animal] = cats
Now here is a bit of magic:
val catsAndDogs = cats :+ Dog("Medor")// catsAndDogs: Vector[Product with Serializable with Animal] = // Vector(Cat(Max), Dog(Medor))
Scala not only allows us to add Dog to Vector[Cat], but it also automatically infers the new collection to be of a Vector[Product with Serializable with Animal] type.
We saw earlier that the parameters of a function are in contravariant ...
Read now
Unlock full access