The Basics of Scala
Topics in This Chapter A1
- 1.1 The Scala Interpreter — page 1
- 1.2 Declaring Values and Variables — page 3
- 1.3 Commonly Used Types — page 4
- 1.4 Arithmetic and Operator Overloading — page 5
- 1.5 Calling Functions and Methods — page 7
- 1.6 The apply Method — page 8
- 1.7 Scaladoc — page 8
- Exercises — page 11
In this chapter, you will learn how to use Scala as an industrial-strength pocket calculator, working interactively with numbers and arithmetic operations. We introduce a number of important Scala concepts and idioms along the way. You will also learn how to browse the Scaladoc documentation at a beginner’s level.
Highlights of this introduction are:
- Using the Scala interpreter
- Defining variables with var and val
- Numeric types
- Using operators and functions
- Navigating Scaladoc
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.
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”.