My favourite Scala compilation error

The error could be illustrated by the following code.

def increase(i: Int) = i + 1
def double(i: Int) = i * 2
val opt = Some(12)
val computed1 = opt.map(increase).map(double)map(increase)
val computed2 = opt.map(increase).map(double)map(increase)
                                 .map(double)

Let's say you had a fairly long computation on options and it worked fine. That is what I have in the line for "computed1". But then you decided that you need to add one more call to the chain. And it does not compile anymore. That is what I have in the line for "computed2". And the error message is: "missing arguments for method increase in object Test; follow this method with `_' if you want to treat it as a partially applied function". Scala complains about the previous function in the chain, the one you have not even touched. Can you spot the actual error?

Of course the real cause is the missing dot (".") prior to the map() call there. Once you see it, everything is obvious. The code used to work because of the Scala's alternative call convention: "instance method single_argument" with (increase) being that single argument. By adding ".map(double)" at the end I was not adding anything to the existing chain, I was adding to the last argument. And the argument becomes "(increase).map(double)" which obviously does not compile.

A very simple one character typo reported as a verbose and totally unrelated error.

Posted On

Category:

Tags: / /