Value classes

Versions: Scala 2.12.1

I am a class storing a single public and immutable value and at runtime I'm allocated on stack. What's my name ?

This new post from "One Scala feature per week" series presents value classes. The very first section mentions shortly value object pattern that is very similar to the main topic of the article. The next part part goes directly to the subject and presents some theoretical and important points about value classes. The 2 next parts shows some examples when value class doesn't and does need allocated memory.

Value object pattern

The idea behind value object pattern consists on representing data per value rather than per reference. It means that 2 different (in terms of memory addresses) value objects with the same value(s) are equal. From this short description you can already deduce that value objects are compared not through the identity (e.g. memory address, a database identifier) but by values they contain.

Value objects are usually small (e.g. amount with currency) and should be immutable in order to keep consistency in the business logic (since compared by values). Even though they could represent few values, they can still contain some helper logic. One of this kind of logic can be Java's String toUpperCase() method.

Value class

Scala's value class is very similar to the pattern described above. It also represents simple values that at JVM's level don't need an allocated place in the heap.

In order to create a value class, the following points need to be respected: