Vals gotcha! — VirtusLab

Immutability in Scala is great. A lot of concerns go away when you use it, but those that remain are not so clear to reason about.

Bartosz Kowalik
Oct 16, 2015 · 2 min read

Actual problem

In every book about Scala you will read something more or less like that: vals are implemented as private fields with public getters. But this is not the full truth about vals. Unfortunately, this public getter is the source of all evil.

What is the actual value and why?

Look at another code snippet showing constructors translated to bytecode

  1. Bar#Bar() calls parent class constructor Foo#Foo() by invokespecial #19
  2. Foo a field is initialized with 1.
  3. Foo#b is initialized with result of Foo#a().

Summary

Could it be done better than that? Java does not provide polymorphic fields at all. Primitives are particularly good example here because default primitves values are inserted instead of null. This leads to non obvious program behaviour at runtime without errors. If it had been a reference type, there would have been an immediate NullPointerException drawing attention to this piece of code.


VirtusLab

Virtus Lab company blog

Bartosz Kowalik

Written by

Scala developer @ VirtusLab

VirtusLab

VirtusLab

Virtus Lab company blog