Some basic data typesIntroduction to ScalaScala uses static typingval variables and var variables

val variables and var variables

Scala has two different kinds of variables: val variables and var variables. val stands for value, and a val variable can never change its value. Once you have defined it, its value will always remain the same:

val m = 17
m = 18      // error!
A var variable, on the other hand, can change its value as often as you want:
var n = 17
n = 18      // ok

val variables do not exist in Python, C, C++, or Java. They belong to a style of programming called functional programming, and exist in programming languages such as LISP (perhaps you have met the let command of Scheme and Racket), Haskell, ML, etc.

In a purely functional program, all variables are val variables. If you want to learn more about this, consider following the Coursera course Functional Programming Principles in Scala.

In a nutshell, val variables are good, because they make it easier to understand and to discuss a program. When you see a val variable defined somewhere in a large function, you know that this variable will always have exactly the same value. If the programmer had used a var variable instead, you would have to carefully go through the code to find out if the value changes somewhere.

It is considered good style in Scala to use val variables as much as possible. For each variable you declare, think careful if you need to make it a var variable.

Some basic data typesIntroduction to ScalaScala uses static typingval variables and var variables