- 1.1 The Scala Interpreter
- 1.2 Declaring Values and Variables
- 1.3 Commonly Used Types
- 1.4 Arithmetic and Operator Overloading
- 1.5 Calling Functions and Methods
- 1.6 The apply Method
- 1.7 Scaladoc
- Exercises
1.2 Declaring Values and Variables
Instead of using the names res0, res1, and so on, you can define your own names:
scala> val answer = 8 * 5 + 2 answer: Int = 42
You can use these names in subsequent expressions:
scala> 0.5 * answer res3: Double = 21.0
A value declared with val is actually a constant—you can’t change its contents:
scala> answer = 0 <console>:6: error: reassignment to val
To declare a variable whose contents can vary, use a var:
var counter = 0 counter = 1 // OK, can change a var
In Scala, you are encouraged to use a val unless you really need to change the contents. Perhaps surprisingly for Java or C++ programmers, most programs don’t need many var variables.
Note that you need not specify the type of a value or variable. It is inferred from the type of the expression with which you initialize it. (It is an error to declare a value or variable without initializing it.)
However, you can specify the type if necessary. For example,
val greeting: String = null val greeting: Any = "Hello"
You can declare multiple values or variables together:
val xmax, ymax = 100 // Sets xmax and ymax to 100 var greeting, message: String = null // greeting and message are both strings, initialized with null