Vals and Vars *

Immutable vs mutable

One of the first lessons that the functional world gives away is that the values we declare (val) are immutable, i.e., they can only be given a value once and cannot be modified afterwards (we’ll see later that this statement has its nuances). Henceforth, if we declared:

val myNumber: Int = 2
myNumber = 3 //Compile-time error

We wouldn’t be able to change its value. This may seem odd at first, but variables (var), commonly used in other programming languages such as Java, are completely discouraged in Scala.

var myNumber: Int = 2
myNumber = 3
println(myNumber) //Prints out '3'

What’s the point in this? If we understand that any pure function is not allowed to maintain any state, then it seems obvious that variables can have no place in them. On the other hand, you might think: ‘Yeah, but the world is not functional: as an example, I/O is essential to configure the execution of a program’… You’re absolutely right. That’s why it is recommended that, if variables need to be used, checks are carried out to see if this is absolutely necessary and if so, they should be placed at the nearest point to the application entry.
For anything else, there’s masterVal

Nounces: Stateful objects.

We said earlier that if a variable is defined as val, its value cannot be modified. We also said that some nounces could be applied to this statement. Let’s assume that we have the following piece of code:

class Foo {
  private var initialized: boolean = false
  def initialize(): Unit = {
    initialized = true
  def isInitialized(): Boolean = initialized

If we do now instantiate a Foo-type object

val immutableFoo = new Foo
immutableFoo.isInitialized() // false
immutableFoo = new Foo //Compile-time error

If we try to reassign its value, we’ll get a compile-time error (nothing new for now). But if we call its initialize method…

immutableFoo.isInitialzed() // false
immutableFoo.isInitialized() // true

…we will have modified its internal state. So, our Foo has become in what’s called a ‘Stateful object’: an object with state. Scala tries to refuse this behaviour but we should not forget that this is the normal thing to do in Java code. Given that one of the facilities of Scala is the integration with Java, the use of Java libraries and frameworks is common practice. Our recommendation is that this pattern is avoided in Scala implementations, but we have to be aware of its likely use in other tools that we might be integrating in our project.

The best of both worlds…

One of the main virtues of Scala (scalaz people would kill us for saying this) is the existence of var.


But had you not said before that var=crap? True. But it is precisely the fact that these kinds of expressions are not forbidden what eases the transition to Scala from other languages such as Java. A transition that might be less traumatic if, at first, the same old constructions are built but with Scala’s syntax for then, further on, adopting a proper functional style.



Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s