Variables in Scala

Scala Tutorial

Senthil Nayagan
1 min readDec 9, 2018

There are three ways you can define variables: val, var, and lazy val.

Val

An immutable (cannot be changed) variable is declared with the keyword val.

val valX = 1 + 1

As it is immutable, we will get a compile error when reassigning a value to val .

Var

A mutable variable is declared with keyword var.

var varX = 1 + 1

We can reassign a new value to varX as it is mutable, but we cannot reassign the variable to a different type — will compile error.

// varX = 2.5 - Compile error as we can't reassign to different type

Lazy Val

Evaluates once, the first time the variable is accessed.

Only vals can be lazy variables.

lazy val lazyValX = 1 + 1

On the first access of lazyValX from somewhere else, the stored expression 1 + 1 is evaluated and the result (2 in this case) is returned.

On subsequent access of lazyValX, no evaluation happens and the stored result of the evaluation was cached and will be returned instead.

scala> val x = { println("x"); 15 }
x
x: Int = 15
scala> lazy val y = { println("y"); 13 }
y: Int = <lazy>
scala> x
res2: Int = 15
scala> y
y
res3: Int = 13
scala> y
res4: Int = 13

Scala Exercises: https://github.com/SenthilNayagan/scala-tutorial

--

--

Senthil Nayagan
Senthil Nayagan

Written by Senthil Nayagan

I am a Data Engineer by profession, a Rustacean by interest, and an avid Content Creator.

No responses yet