Variables in Scala
Our first program will demonstrate variable declaration and initialization in Scala. Here’s the full source code:
In Scala, variables are explicitly declared and used by the compiler to check type-correctness of function calls.
var
declares a mutable variable. You can change its value later in the program.
You can declare multiple variables at once, but in Scala, they will all have the same value.
Scala will infer the type of initialized variables, so you don’t always need to specify the type explicitly.
Unlike some other languages, Scala doesn’t allow uninitialized variables. Instead, we can use Option
to represent a potentially uninitialized value. Here, we use getOrElse(0)
to print 0 if the value is not set.
The val
keyword is used to declare immutable variables (constants). Once a value is assigned to a val
, it cannot be changed.
To run the program, save it as Variables.scala
and use the Scala compiler (scalac
) to compile it, then run it with scala
:
This example demonstrates basic variable declaration and usage in Scala. As you continue learning, you’ll discover more advanced features and idioms specific to Scala.