Welcome! Today, we're delving into Scala variables, critical elements in any programming language. They serve as containers that store and handle data. In this lesson, we'll explore what they are, learn about assigning values, naming them, and discuss the nature of constants in Scala.
A variable is a slot in memory that holds data; its content can change during a program's execution. For example, in the snippet below, the value "Alice"
held by myName
is replaced by "Bob"
:
Scala features two types of variables - val
, which is immutable (cannot be changed once assigned), and var
, which is mutable (can be changed after its initial assignment).
As was mentioned earlier, in Scala, you can reassign values to variables declared with var
. However, variables declared with val
are immutable. Let's assign and reassign a value to myAge
to see this action:
