Scala Variables
A variable is a named storage place that holds a value in a program. Scala has two kinds, val for a value that stays the same and var for a value that can change.
A val stores a value under a name
The name name holds the text Ana. Printing the name prints the stored text.
@main def main(): Unit =
val name = "Ana"
println(name)A var can be reassigned to a new value
The var score starts at 10. A new assignment changes it to 15.
@main def main(): Unit =
var score = 10
println(score)
score = 15
println(score)A type can be inferred or written out
The count line writes its Int type after the name. The price line lets the compiler work out the type from 2.5.
@main def main(): Unit =
val count: Int = 7
val price = 2.5
println(count)
println(price)Example
@main def main(): Unit =
val city = "Paris"
var visits = 1
println(city)
println(visits)
visits = 2
println(visits)Key points
- val: a val holds a value that cannot be reassigned after it is set.
- var: a var holds a value that can be changed with a new assignment.
- Assignment: the = sign stores the value on the right under the name on the left.
- Type inference: the compiler works out the type of a value from what is assigned.
- Type annotation: a type can be written after the name, like val count: Int = 7.
- Use: a stored value is used later by writing its name.
In this example, the val city stores the text Paris and the var visits stores 1. The program prints both values, then changes visits to 2 and prints it again.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Which keyword creates a value that can be reassigned later?