Scala function error “Type mismatch” in Intellij Idea vs Scala Eclipse

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
As you can see, curly braces are not mandatory when all those elements are put in one line.
When you put that code in Scala worksheet both in Intellij Idea and Scala Eclipse (Scala Eclipse IDE) everything is all right. Code compiles and runs.

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)
That is the point where I spot difference in behavior between those two IDE.
While Scala Eclipse runs that code without any error, Intellij Idea gets stuck with the following error message:
error: type mismatch;
   found   : Unit
   required: Int
             if (list == Nil) 0
I am sure that that error message does not tell much to Scala beginners about the source of the problem.
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.

Leave a Reply

Your email address will not be published. Required fields are marked *