Pitfalls for Java programmers new to Scala: void vs Unit
As a newbie in Scala coming from a mostly Java background, I ran into a non-obvious problem.
Having some test code like this:
def foo() : Unit = { val bar = 5 }The Scala compiler would complain with: "error: block must end in result expression, not in definition".
I knew what the compiler meant: it was expecting a value or an expression that it could treat as the return value of the function but I did not understand why. I assumed that Unit was like void, surely there is no return value required?
The fix is obvious, instead of a val declaration like this, just have a statement that returns a value. Like say:
def foo() : Unit = { 5 }Unit is an actual return type and so the compiler expects something. The actual explanation required some Googling and a blog post by James Iry goes into quite some detail on the topic.
From a design point of view it is a bit of the functional nature of Scala peeking through: Java programmers are used to writing methods that just have a few side effects but don't return anything. In a pure functional context - no side effects - a function that doesn't return anything doesn't have to be executed and therefore has no reason to exist.
So, Java programmers, remember: void != Unit.
