Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 1. The Basics > The Scala Interpreter

1.1. The Scala Interpreter

To start the Scala interpreter:

  • Install Scala.

  • Make sure that the scala/bin directory is on the PATH.

  • Open a command shell in your operating system.

  • Type scala followed by the Enter key.

Tip

Don’t like the command shell? There are other ways of running the interpreter—see http://horstmann.com/scala/install.


Now type commands followed by Enter. Each time, the interpreter displays the answer. For example, if you type 8 * 5 + 2 (as shown in boldface below), you get 42.

scala> 8 * 5 + 2
res0: Int = 42

The answer is given the name res0. You can use that name in subsequent computations:

scala> 0.5 * res0
res1: Double = 21.0
scala> "Hello, " + res0
res2: java.lang.String = Hello, 42

As you can see, the interpreter also displays the type of the result—in our examples, Int, Double, and java.lang.String.

You can call methods. Depending on how you launched the interpreter, you may be able to use tab completion for method names. Try typing res2.to and then hit the Tab key. If the interpreter offers choices such as

toCharArray   toLowerCase   toString   toUpperCase

this means tab completion works. Type a U and hit the Tab key again. You now get a single completion:

res2.toUpperCase

Hit the Enter key, and the answer is displayed. (If you can’t use tab completion in your environment, you’ll have to type the complete method name yourself.)

Also try hitting the ↑ and ↓ arrow keys. In most implementations, you will see the previously issued commands, and you can edit them. Use the ←, →, and Del keys to change the last command to

res2.toLowerCase

As you can see, the Scala interpreter reads an expression, evaluates it, prints it, and reads the next expression. This is called the read-eval-print loop, or REPL.

Technically speaking, the scala program is not an interpreter. Behind the scenes, your input is quickly compiled into bytecode, and the bytecode is executed by the Java virtual machine. For that reason, most Scala programmers prefer to call it “the REPL”.

Tip

The REPL is your friend. Instant feedback encourages experimenting, and you will feel good whenever something works.

It is a good idea to keep an editor window open at the same time, so you can copy and paste successful code snippets for later use. Also, as you try more complex examples, you may want to compose them in the editor and then paste them into the REPL.