Learn Scala 3 Fast: Variables: var Fields

When you need to create a variable whose value can change over time, define the field as a var instead of val:

// assign a value to 'name'
var name = "Reginald Kenneth Dwight"

Because name is a var, you can later change its contents:

// some time later, give 'name' a new value
name = "Elton John"

As mentioned in the previous lesson, if you try to do this with a val field you’ll generate an error, but with var fields this is perfectly legal.

The new value must be the same type

As you’ll see in the upcoming lessons, Scala is a strongly-typed language, and one thing this means is that the variable name must always hold a String value. So this reassignment works:

name = "Fred"

but this fails:

name = 1   // compiler error

As you’ll soon see, this is because "Fred" is an instance of a class named String, so name is created as a String variable. The attempt to reassign a 1 to name fails because 1 is an instance of a different class named Int.

Keeping track of data types is one way that Scala is a strongly-typed and type-safe language. Because it’s type-safe, the Scala compiler will catch these errors at compile time. Or, if you use an IDE, it will catch them as you type.

But always start with val

Using val and var are the two ways to create variables in Scala. And now that you’ve seen both approaches, it’s important to reiterate this point:

  1. Always declare variables as val, unless
  2. The variable really does need to vary over time, in which case you should create it as a var

If you follow this one simple rule, you’ll find that you really don’t need to use var fields that often. That makes your code safer because you don’t have to worry about the variable being unexpectedly changed somewhere else in your code.

TIP: This was something I never even thought about with Java. Maybe because I didn’t take computer science classes in college it never occurred to me to specifically declare my intent like this, i.e., to mark 80-90% (or more) of my Java variables as final. This is just one of the ways Scala will change the way you think about programming, and help make you a better programmer.


The exercises for this lesson are available here.

books by alvin