Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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
  • + Share This
  • 🔖 Save To Your Account