Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

4. Variables

Scala has two types of variables.

Table 1. Variables in Scala

DeclarationDescription
var defines a mutable variable, e.g. the value of this variable can be changed after the first assignment.
val defines a variable which get its value assigned during declaration and which is immutable, e.g. the assigned value cannot be changed later.

The functional programming style of Scala emphasis the usage of val variables.

Scala is a strongly typed language, e.g. each variable has a specific type. The type declaration is optional; if no type is defined during declaration then the variable will get the type of the initial assigned value. This is called "type inference".

Create a scala project "de.vogella.scala.variables" and try the following code.

			
object VariablesTest extends Application {

  val firstName = "Lars"
  val lastName = "Vogel" 
  var test = "changable"
  println(firstName)
}