Think in Scala: val or var?

Pankaj Patil
Nov 24, 2021

When in doubt, you should always try to use val instead of var.

Having immutable values makes your programs safe from concurrency inconsistency in exchange for some additional memory allocation; most of the time, you will not notice this extra memory usage thanks to the JVM’s garbage collection.

Using mutable structures makes your programs challenging to test and reason about; you need to pay attention to how processes share data and how they evolve. Mutable structures may be more performant, but they also expose your code to complex concurrency issues such as data inconsistency, deadlocks, and resource starvation.

Before choosing to stick with a var, you should make sure you have tried everything else in your book of tricks; variables should be your last and least desirable option.

--

--

Pankaj Patil

Software Engineer | Blogger | Reader | Writer| Political and Social Activist