Chapter 23

For Expressions Revisited

Chapter 16 demonstrated that higher-order functions such as map, flatMap, and filter provide powerful constructions for dealing with lists. But sometimes the level of abstraction required by these functions makes a program a bit hard to understand. Here's an example. Say you are given a list of persons, each defined as an instance of a class Person. Class Person has fields indicating the person's name, whether (s)he is male, and his/her children. Here's the class definition:

  scala> case class Person(name: String, 
                           isMale: Boolean, 
                           children: Person*)

Here's a list of some sample persons:

  val lara = Person("Lara"false)
  val bob = Person("Bob"true)
  val ...

Get Programming in Scala, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.