Back in my Java days, I remember writing a lot of filtering + cast code like the following (which does not always indicate that good design choices were made in my projects, but that’s another debate ;-)) :

public TransformedElement transform(SpecialElement se) { ... }
public boolean accept(SpecialElement se) { ... }
...
List<Element> elements = ...;
List<TransformedElement> result = new ArrayList<TransformedElement>();
for (Element element : elements) {
    if (element instanceof SpecialElement) {
        SpecialElement se = (SpecialElement)se;
        if (accept(se))
            result.add(transform(se));
    }
}

In Scala of course, you don’t need to write loops for such collection transformations.

A naive translation would look like :

class Element
class SpecialElement extends Element
class TransformedElement
def accept(se: SpecialElement) = true
def transform(se: SpecialElement) = new TransformedElement
val elements = Seq[Element]() // ...
val results1 =
  elements.
    filter(_.isInstanceOf[SpecialElement]).
    map(_.asInstanceOf[SpecialElement]).
    filter(accept).
    map(transform)

Another (differently) naive translation could be :

val results2 =
  elements.
    flatMap(_ match {
      case se: SpecialElement if accept(se) => Some(transform(se))
      case _ => None
    })

(flatMap will extract the transformed elements from the Some and will skip the None)

Still a bit verbose, right ? Now here’s my favorite rewrite, which I’ve only recently become accustomed to :

val results3 =
  elements collect { case se: SpecialElement if accept(se) => transform(se) }

The collect method takes a PartialFunction as argument and maps the values defined for this partial function over it, skipping those outside the definition domain. And case ‘statements’ are partial functions (which definition domain is obviously defined by matching patterns).

Given a partial function pf, the following code :

val pf: PartialFunction[A, B] = ...
someCollection.collect(pf)

Is roughly equivalent to :

someCollection.filter(pf.isDefinedAt _).map(pf)

Want to learn more in that style ? Go read the online Scala API Documentation, especially Seq[T] (one of the base collection traits) and Option[T] (you might not see how useful it is yet, but Option rulez… and has a collect method ;-)).

PS: note that collect is defined in the Traversable[T] trait, which is inherited by Seq[T] and hence implicitely available from Array[T] and any collection, but I just don’t use Traversable much as it’s a bit too generalistic. Anyway on these collections matters, I urge the readers to rush to Martin Odersky and Lex Spoon’s documentation on the architecture of the new Scala Collections, which you should definitely read before writing your next line of Scala.