14.1. Getting Started with the Scala REPL

Problem

You want to get started using the Scala REPL, including understanding some of its basic features, such as tab completion, starting the REPL with different options, and dealing with errors.

Solution

To start the Scala REPL, type scala at your operating system command line:

$ scala

You’ll see a welcome message and Scala prompt:

Welcome to Scala version 2.10.0
Type in expressions to have them evaluated.
Type :help for more information.

scala> _

Welcome, you’re now using the Scala REPL.

Inside the REPL environment, you can try all sorts of different experiments and expressions:

scala> val x, y = 1
x: Int = 1
y: Int = 1

scala> x + y
res0: Int = 2

scala> val a = Array(1, 2, 3)
a: Array[Int] = Array(1, 2, 3)

scala> a.sum
res1: Int = 6

As shown in the second example, if you don’t assign the result of an expression to a variable, the REPL creates its own variable, beginning with res0, then res1, etc. You can use these variable names just as though you had created them yourself:

scala> res1.getClass
res2: Class[Int] = int

Writing tests like this in the REPL is a great way to run experiments outside of your IDE or editor.

There are a few simple tricks that can make using the REPL more effective. One trick is to use tab completion to see the methods that are available on an object. To see how tab completion works, create a String object, type a decimal, and then press the Tab key. With Scala 2.10, the REPL shows that more than 30 methods are available on ...

Get Scala Cookbook now with O’Reilly online learning.

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