Scala Covariance

Let's see what is Covariance.

We are going to learn what it is and when to use it.

So, what is variance ? This is a concept related to types and how they are connected to each other. It is about inheritance. We saw before the relationship between a parent class and a child class. In functional programming we also talk about sub-type.

You can see in the start of the exercise what we encountered before related to parent and child class with inheritance.

Then we use a “normal” generic class without the covariance. You see that using a F[A] as a F[B] do not with and you are getting type mismatch with some explanation : found F[A] , required F[B]. This is expected, the types are different even tho they share a common parent, they are different.

However, why couldn't you use a F[A] as a F[P] if P is the parent of A ? This time the error is a lot more detailed:

type mismatch; found   : F[A] required: F[P] Note: A <: P, but trait F is invariant in type A. You may wish to define A as +A instead. (SLS 4.5)

We recognize one symbol we saw before: <: which talks about the relationship between the two types.

In the last part of the exercise you make a covariant trait using the syntax:

trait MyTrait[+A]

The +A means that the trait is now covariant for A.

And now, what was failing before is working. We are able to use F[A] as F[P].

Hope that was of help to understand what the +A means when you encounter it and how to solve some exception you might have seen ! See you next time.

Reveal more information and clues
Load Exercise