Book Image

Professional Scala

By : Mads Hartmann, Ruslan Shevchenko
Book Image

Professional Scala

By: Mads Hartmann, Ruslan Shevchenko

Overview of this book

This book teaches you how to build and contribute to Scala programs, recognizing common patterns and techniques used with the language. You’ll learn how to write concise, functional code with Scala. After an introduction to core concepts, syntax, and writing example applications with scalac, you’ll learn about the Scala Collections API and how the language handles type safety via static types out-of-the-box. You’ll then learn about advanced functional programming patterns, and how you can write your own Domain Specific Languages (DSLs). By the end of the book, you’ll be equipped with the skills you need to successfully build smart, efficient applications in Scala that can be compiled to the JVM.
Table of Contents (12 chapters)

Abstracting on Sequences


All Scala collections descend from a common trait called Traversable. The design adopted for Scala collections allows one to use higher-order functions similarly in nearly all collections, with proper return types in specific instances. Treating collections as sequences, or as containers of elements, allows one to use different data structures seamlessly.

The Traversable Trait

At the root of the collections hierarchy is the Traversable trait. The Traversable trait has a single abstract method:

def foreach[U](f: Elem => U)

The implementation of this method is sufficient for the Traversable trait to provide a series of useful higher-order methods.

We would like to focus on the map operations. The map method takes a function and applies it to every element of the collection.

Let's experiment with the map method in the Scala REPL and show how it applies to different types of collections. For now, create a function that multiplies an integer by 2 and apply...