Variables and Definitions

Variables and definitions form the building blocks to scala. Note the biggest difference between the two is actually how they’re evaluated. Most variables are evaluated when defined, whilst def is evaluated on call. There are exceptions mentioned below

Variables

Scala has two types of variables, vals and vars. A val is similar to a final variable in java. Once initialised, a val can never be reassigned. A var can be reassigned throughout its lifetime

val msg = "Hello, World"
var msgOther = "Also, hello world!"

Note that in the above, there is an example of Scala’s type inference. You do not need to explicitly state what data type is being used, Scala’s compiler will be able to infer it.

Lazy

lazy val age = 27

Note, if we were to decompile the equivalent Java code that gets generated for every lazy val, we would received:

		private int age;
    private volatile boolean bitmap$0;
    
    private int age$lzycompute() {
        synchronized (this) {
            if (!this.bitmap$0) {
                this.age = 27;
                this.bitmap$0 = true;
            }
        }
        return this.age;
    }
    
    public int age() {
        return this.bitmap$0 ? this.age : this.age$lzycompute();
    }lazy

The compiler introduces a monitor synchronized (this) {} to guarantee that variable initializes only once, and a bitmap flag to track the initialization status. This can create deadlocks if not careful

Definitions

Here’s how to define functions in Scala