If you divide your problem into subtasks, you can find a more idiomatic version. Do you want to
- find all instances of
T in Iterable[Any] - add them to
T to make the compiler happy - find the first matching element
For the first point, you can easily use the filter method on Iterator . So you have
it.iterator.filter(x => clazz.isInstance(x))
which returns you an Iterator[Any] that contains only T s. Now convince the compiler:
it.iterator.filter(x => clazz.isInstance(x)).map(x => x.asInstanceOf[T])
Ok, now you have Iterator[T] - so you just need to find the first element that executes your predicate:
def findMatch[T](it: Iterable[Any], clazz: Class[T], pred: T => Boolean): Option[T] = it.iterator.filter(x => clazz.isInstance(x)) .map(x => x.asInstanceOf[T]) .find(pred)
source share