Scala self-referred type

Let's dive more into generic type and self-referred type.

The use case is how to use the children Type in the Parent trait safely.

Sorry for the long exercise but I really wanted to show step by step how we end up with this solution based on the problem encountered.

In the first example, without doing anything, we are able to change the output type to the child type when we override the method but not the input type.

In the second example we now have information about the child type from inside the parent trait but there are not guarantee thatAis the right children, it could be any children.

With the final solution,Amust be in used in the child type which guarantee that it is the child.

Let's summaries the syntax:

trait Name[A <: Name[A]]{ this: A =>

}

Hopefully that will help you make the compiler your friend and catch more mistake at compile time rather than at runtime !

Reveal more information and clues
Load Exercise