Scala Vector transformer methods (syntax, examples)

This page contains a large collection of examples of how to use Scala Vector class transformer methods.

Transformer methods

A transformer method is a method that constructs a new collection from an existing collection.

Methods on the Scala collections classes, organized by category

When I wrote the Scala Cookbook, I gave each recipe and then each chapter my full attention. I thought that if I wrote each recipe as well as possible, and included important recipes in each chapter, well, I wanted each chapter to be worth the price of the entire book. That was my goal.

As a result of this effort -- and perhaps to the chagrin of my editor -- the Scala collections chapters ended up being 130 pages in length.

Scala: How to combine map and flatten with flatMap

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.16, “How to Combine map and flatten with flatMap”


When you first come to Scala from an object-oriented programming background, the flatMap method can seem very foreign, so you’d like to understand how to use it and see where it can be applied.


Use flatMap in situations where you run map followed by flatten. The specific situation is this:

How to flatten a List of Lists in Scala with flatten

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 10.15, “How to Flatten a List of Lists in Scala with flatten


You have a list of lists (a sequence of sequences) and want to create one list (sequence) from them.


Use the flatten method to convert a list of lists into a single list. To demonstrate this, first create a list of lists:

A collection of Scala ‘flatMap’ examples

Scala flatMap FAQ: Can you share some Scala flatMap examples?

Sure. When I was first trying to learn Scala, and cram the collections' flatMap method into my brain, I scoured books and the internet for great flatMap examples. Once I had a little grasp of it I started creating my own examples, and tried to keep them simple.

Using flatMap on a list of Strings

The following examples show the differences between map and flatMap on a sequence of String: