liveBook · Manning

Filtering

As explained in Functional Programming in Scala, Second Edition

An Option filter retains a present value only when it satisfies a Boolean-valued predicate, otherwise producing None.

Filtering keeps a value only when a predicate accepts it. On a List, it removes elements that fail the predicate; on an Option, it preserves Some when the predicate is true and produces None otherwise. section 3.3.3 section 4.3.1

Filtering an optional department

A lookup can remain inside Option while filtering its result: lookupByName("Joe").map(_.department).filter(_ != "Accounting").getOrElse("Default Dept"). The computation proceeds only when the employee exists and the department is not Accounting; otherwise it selects the default. section 4.3.1

The Option implementation makes the behavior explicit: flatMap applies a function that returns Some or None, so filter returns Some(a) when f(a) succeeds and None when it fails. This mirrors the List version and lets filtering compose with map, flatMap, and getOrElse without explicit pattern matching. section 4.6

Listing 4.2 The Option data type
enum Option[+A]:
  case Some(get: A)
  case None
 
  def map[B](f: A => B): Option[B]                   #1
  def flatMap[B](f: A => Option[B]): Option[B]       #2
  def getOrElse[B >: A](default: => B): B            #3
  def orElse[B >: A](ob: => Option[B]): Option[B]    #4
  def filter(f: A => Boolean): Option[A]             #5

Use the Option interface to compare filtering with transformation, flattening, default selection, and fallback. section 4.3.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines filtering, demonstrates chained use, and derives Option.filter through flatMap; it stops short of broader implementation optimization.
Examples
Demonstrates removing odd integers and excluding the Accounting department from an optional employee lookup.
What you can do after
Apply it via List.filter and Option.filter to retain values satisfying Boolean predicates.
How it connects
Connects filtering to Option, List, predicates, map, flatMap, getOrElse, and higher-order functions.

Also explained in

Compare how 33 books explain filtering →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.