If I want to narrow, say, Iterable[A] for all elements of a certain type (for example, String ), I can do:
as filter { _.isInstanceOf[String] }
However, obviously, it is advisable to use this as an Iterable[String] , which can be done using map :
as filter { _.isInstanceOf[String] } map { _.asInstanceOf[String] }
This is pretty ugly. Of course, I could use flatMap instead:
as flatMap[String] { a => if (a.isInstanceOf[String]) Some(a.asInstanceOf[String]) else None }
But I'm not sure if this is more readable! I wrote a narrow function that can be used with implicit conversions:
as.narrow(classOf[String])
But I was wondering if there is a better built-in mechanism that I forgot. In particular, it would be nice to narrow down a List[A] to a List[String] , and not to Iterable[String] , as it will be with my function.
source share