Today we are going to combine several things we know to learn about extractor 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 the List
that 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 the implicit
proof using the syntax: A : PROOF
. In this case we want B
to be a ClassTag
as well as being a child of A
. Which is why we now have this syntax: B <: A: ClassTag
.
Have you tried removing the ClassTag
? You are seeing a Warning
talking about abstract 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 be ClassTag
.
Now that we have our extractor, we can filter down the List[Animal]
to only keep the Cat
or the Dog
!
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 !