Scala Covariance

Let's see what isCovariance.

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 aboutsub-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 aF[A]as aF[B]do not with and you are gettingtype mismatchwith 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 aF[A]as aF[P]ifPis the parent ofA? 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+Ameans that the trait is nowcovariantforA.

And now, what was failing before is working. We are able to useF[A]asF[P].

Hope that was of help to understand what the+Ameans 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