Scala extractor pattern

Today we are going to combine several things we know to learn aboutextractor pattern.

It might be a bit complicated but I am sure you are going to be fine !

The goal here is to be able to only keep the element of theListthat are of a given type.

We start from a list of type A :List[A]. And we want to keep the element of type B, with B being the child class of A. We saw few exercise ago the syntax :B <: A.

We also saw theimplicitproof using the syntax:A : PROOF. In this case we wantBto be aClassTagas well as being a child ofA. Which is why we now have this syntax:B <: A: ClassTag.

Have you tried removing theClassTag? You are seeing aWarningtalking aboutabstract type B is unchecked since it is eliminated by erasure. We are going to dive deeper into this in another episode. But for now, you only need to know that to mitigate the "type erasure" problem, we need to introduce a proof to beClassTag.

Now that we have our extractor, we can filter down theList[Animal]to only keep theCator theDog!

I am sure you are going to need this pattern in one of your project one day ! Just let us know on the Discord server how that has been useful to you !

Reveal more information and clues
Load Exercise