Essential Scala

Noel Welsh and Dave Gurnell

Version 1.3, April 2017

Foreword

This book is aimed to programmer learning Scala for the first time. We assume you have some familiarity with an object-oriented programming language such as Java, but little or no experience with functional programming.

Our goal is to describe how to use Scala in-the-small. To this end our focus is on the core patterns used in idiomatic Scala code, and we introduce Scala’s features in the context of the patterns they enable. We are not aiming for exhaustive coverage of Scala’s features, and this text is not a reference manual.

Except for a few exercises we don’t rely on any external libraries. You should be able to complete all the problems inside with only a text editor and Scala’s REPL, or an IDE such as the Scala IDE for Eclipse or IntelliJ IDEA.

Essential Scala was created by Noel Welsh and Dave Gurnell of Underscore. It was built using Underscore’s eBook Template, plain text, and a deep and profound love of functional programming.

Conventions Used in This Book

This book contains a lot of technical information and program code. We use the following typographical conventions to reduce ambiguity and highlight important concepts:

Typographical Conventions

New terms and phrases are introduced in italics. After their initial introduction they are written in normal roman font.

Terms from program code, filenames, and file contents, are written in monospace font. Note that we do not distinguish between singular and plural forms. For example, might write String or Strings to refer to the java.util.String class or objects of that type.

References to external resources are written as hyperlinks. References to API documentation are written using a combination of hyperlinks and monospace font, for example: Option.

Source Code

Source code blocks are written as follows. Syntax is highlighted appropriately where applicable:

object MyApp extends App {
  println("Hello world!") // Print a fine message to the user!
}

Some lines of program code are too wide to fit on the page. In these cases we use a continuation character (curly arrow) to indicate that longer code should all be written on one line. For example, the following code:

println("This code should all be written ↩
  on one line.")

should actually be written as follows:

println("This code should all be written on one line.")

Callout Boxes

We use three types of callout box to highlight particular content:

Tip callouts indicate handy summaries, recipes, or best practices.

Advanced callouts provide additional information on corner cases or underlying mechanisms. Feel free to skip these on your first read-through—come back to them later for extra information.

Warning callouts indicate common pitfalls and gotchas. Make sure you read these to avoid problems, and come back to them if you’re having trouble getting your code to run.

Thanks

Many thanks to Richard Dallway and Jonathan Ferguson, who took on the herculean task of proof reading our early drafts and helped develop the rendering pipeline that produces the finished book.

Thanks also to Danielle Ashley, who updated all of the code samples to use Tut and increased our code quality 100% overnight!

Thanks also to Amir Aryanpour, Konstantine Gadyrka, Rebecca Grenier, Joe Halliwell, Jon Pearce, Jason Scott, N. Sriram, Daniel Watford, and Audrey Welsh who sent us corrections and suggestions while the book was in early access. Knowing that our work was being used made the long haul of writing worthwhile.

1 Getting Started

Throughout this book we will be working with short examples of Scala code. There are two recommended ways of doing this:

  1. Using the Scala console (better for people who like command lines)

  2. Using Worksheets feature of Scala IDE (better for people who like IDEs)

We’ll walk through the setup for each process here.

1.1 Setting up the Scala Console

Follow the instructions on http://scala-lang.org to set Scala up on your computer. Once Scala is installed, you should be able to run an interactive console by typing scala at your command line prompt. Here’s an example from OS X:

dave@Jade ~> scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala>

You can enter individual expressions at the scala> prompt and press Enter to compile and execute them:

scala> "Hello world!"
res0: String = Hello world!

1.1.1 Entering Single-Line Expressions

Let’s try entering a simple expression:

scala> 1 + 2 + 3
res1: Int = 6

When we press Enter, the console responds with three things:

As we will see in the next chapter, every expression in Scala has a type and a value. The type is determined at compile time and the value is determined by executing the expression. Both of these are reported here.

The identifier res1 is a convenience provided by the console to allow us to refer to the result of the expression in future expressions. For example, we can multiply our result by two as follows:

scala> res1 * 2
res2: Int = 12

If we enter an expression that doesn’t yield a useful value, the console won’t print anything in response:

scala> println("Hello world!")
Hello world!

Here, the output "Hello world!" is from our println statement—the expression we entered doesn’t actually return a value. The console doesn’t provide output similar to the output we saw above.

1.1.2 Entering Multi-Line Expressions

We can split long expressions across multiple lines quite simply. If we press enter before the end of an expression, the console will print a | character to indicate that we can continue on the next line:

scala> for(i <- 1 to 3) {
     |   println(i)
     | }
1
2
3

Sometimes we want to enter multiple expressions at once. In these cases we can use the :paste command. We simply type :paste, press Enter, and write (or copy-and-paste) our code. When we’re done we press Ctrl+D to compile and execute the code as normal. The console prints output for every expression in one big block at the end of the input:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val x = 1
val y = 2
x + y

// Exiting paste mode, now interpreting.

x: Int = 1
y: Int = 2
res6: Int = 3

If we have Scala code in a file, we can use :paste to paste the contents of the file into the console. This is much more convenient than re-entering expressions in the console. For example, with a file named example.scala containing 1 + 2 + 3 we can use :paste like so:

scala> :paste example.scala
Pasting file example.scala...
res0: Int = 6

1.1.3 Printing the Type of an Expression

One final tip for using the console. Occasionally we want to know the type of an expression without actually running it. To do this we can use the :type command:

scala> :type println("Hello world!")
Unit

Notice that the console doesn’t execute our println statement in this expression. It simply compiles it and prints out its type, which in this case is something called Unit.

Unit is Scala’s equivalent of void from Java and C. Read Chapter 1 to find out more.

1.2 Setting up Scala IDE

Scala IDE is a plugin that adds Scala language support to Eclipse. A complete version of Scala IDE with Eclipse is also available as a standalone bundle from http://scala-ide.org. This is the easiest way to install the software so we recommend you install the standalone bundle for this course.

Go to http://scala-ide.org now, click the Get the Bundle button, and follow the on-screen instructions to download Scala IDE for your operating system: