Using Scala we can define a function in a form when name and parameters are specified followed by the definition of the function body.
For example:
def abs(x: Double) = if (x < 0) -x else x
The previous example was very simple. However, functions are more complex in real life so there is no way to stick them in one line. It is not a problem at all, you define multiline functions simply by embracing the function body in curly braces:
def listLength(list: List[_]): Int = { if (list == Nil) 0 else 1 + listLength(list.tail) }
Code of course compiles and runs both in Intellij Idea and Scala Eclipse.
What happens if you omit the braces?
def listLength(list: List[_]): Int = if (list == Nil) 0 else 1 + listLength(list.tail)
Let’s investigate the error message more deeply.
Firstly, find out what type Unit is.
Type Unit is similar to what is known in Java as void. In Java void means that function does not return anything. However, every method in Scala returns a value. To deal with the situation when Scala function does not have anything to return, type Unit was introduced. Eventually Unit is defined on the bytecode level as void, but in Scala source level it is still a type.Come back to the error message. It says that expected returned type is Int but the function returns Unit in fact. What probably happened is situation, when only line:
if (list == Nil) 0
is interpreted, Scala adds the else statement in that form:
else ()
where the mentioned rule of returning Unit when there is nothing to return, is applied.
So the rewritten if finally looks as follows:
if (list == Nil) 0 else ()
If part returns Int, while else part returns Unit. More general type is taken and the whole function tries to return Unit while expecting Int from function definition.
I met that problem when trying to run in Intellij Idea the code example presented in Scala Eclipse. Multiline function was coded without curly braces and only Intellij Idea thrown the error presented.