Scala Variables

Jakob Jenkov
Last update: 2014-05-25

Scala variables come in two shapes. Values and variables. A value variable is really just a constant, meaning once assigned, you cannot change its value. It is immutable in other words. A regular variable on the other hand, is mutable, meaning you can change its value.

Declaring var and val Variables

Here is how you declare these two types of variables:

var myVar : Int = 0;

val myVal : Int = 1;

The first variable, myVar, is declared using the keyword var. This means that it is a variable that can change value.

The second variable, myVal, is declared using the keyword val. This means that it is a value, a constant, that cannot change value once assigned.

Variable Types and Type Inference

The examples earlier in this text specified the type of the variable after the variable name, separated by a colon. In the example below I have repeated the declarations from earlier, and marked the type declarations in bold:

var myVar : Int = 0;

val myVal : Int = 1;

The type of a variable is specified after the variable name, and before any initial value.

When you assign an initial value to a variable, the Scala compiler can figure out the type of the varible based on the value assigned to it. This is called type inference. Therefore, you could write these variable declarations like this:

var myVar = 0;
val myVal = 1;

If, however, you did not assign an initial value to the variable, the compiler cannot figure out what type it is. Therefore, you have to explicitly specify the type if you do not assign an initial value to the variable. Here is how it looks:

var myVar :Int;
val myVal :Int;

Fields, Parameters and Local Variables

Variables in Scala can exist in 3 different roles. As fields, as method parameters and as local variables. There are no static variables in Scala.

Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object, depending on what access modifiers the field is declared with. Fields can be both val's and var's.

Method parameters are variables which values are passed to a method when the method is called. Method parameters are only accessible from inside the method - but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always val's.

Local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both var's and val's.

Jakob Jenkov

Featured Videos

Core Software Performance Optimization Principles


Java Persistence
Close TOC

All Trails

Trail TOC

Page TOC