In every programming language you create variables, and in Scala you create new variables with the val
keyword. For example, this is how you create a String
:
val firstName = "Alvin"
In the REPL you can print the value in the variable firstName
like this:
scala> println(firstName)
Alvin
Taking this a little further, given these two variables:
val firstName = "Alvin"
val lastName = "Alexander"
you can use those variables to create a new variable named fullName
like this:
val fullName = firstName + " " + lastName
This is what you see when you print the fullName
variable in the REPL:
scala> println(fullName)
Alvin Alexander
As you can infer from the examples so far, the general syntax for creating a new variable looks like this:
val theVariableName = theVariableValue
TIP: As shown in these examples, in Scala the standard is to create variable names using camel case, like
firstName
,lastName
, etc. (Conversely, we do not name themfirst_name
andlast_name
.)
You can’t modify val fields
An important thing about val
fields is that they are immutable, meaning that they can’t be changed. So if you create a val
variable like this:
val x = 1
you can’t update it to a new value later. If you try to give x
a new value in the REPL you’ll see an error message like this:
x = 2 // ERROR: Reassignment to val x
A val
field in Scala is similar to a final
field in Java, and like a const
field in JavaScript.
Variable as in algebra
If it seems unusual that a variable can’t vary, it’s important to know that a val
field is a “variable” in the algebraic meaning: just like in algebra, once you assign a value to a variable, it can’t be changed.
This may seem like a limitation, but I ended up learning a ton about programming by following this one simple rule:
Make every variable in Scala a
val
field, unless you have a good reason not to.
When you truly need a variable whose value can be modified (mutated), see the next lesson.
REPL experiments
I always recommend experimenting with things, and to help you get started, here are some experiments you can try in the REPL:
val a = 1
val b = (a + 2) * 2
b = 7 // this is an intentional error
val c = "hello"
Exercises
The exercises for this lesson are available here.