first of all, I know many resources that explain the issue with type erasure, how to use ClassTags, TypeTags, etc... Yet, in this case I would kindly ask to focus on an exact problem, and suggest the best solution for it. Changin the problem is not considered to be a solution (yes, if the system could be re-modeled, the problem won't exist on the same scale).
The Problem
We have some elements elements: Iterator[Any]. We expect that some of the elements are collections (iterables) of our custom type, and we wat to do something with them. What is the best way to collect such elements? The solution that I came up with is
elements
.withFilter {
case iter: Iterable[_] =>
iter.forall(_.isInstanceOf[MyCustomElementTrait])
case _ => false
}
.map(_.asInstanceOf[Iterable[MyCustomElementTrait]])
Remarks
The elements originate from a case class productIterator, but again the goal is not to change the outer implementation, but to find a better solution for "collecting" the iterables of a certain type.
I've spent countless hours trying to solve this with TypeTags and WeakTypeTags, but I completely failed. Thus I would be thankful to know if this is the only way to solve the problem, or there is something more elegant.
collectis the natural choice for this, so just add an explicit type check to overcome erasure.