Giuseppe Scopelliti Giuseppe Scopelliti - 1 year ago 80
Scala Question

Block statements in anonymous Scala function

I've created this simple anonymous function

var b = (x : Int) => if(x % 2 == 0) x + 1 else x

and it works great. After that I tried to add another statement after the if and before the

var b = (x : Int) => if(x % 2 == 0) println(x) x + 1 else x

and a that point I received the following compiler error

Cannot resolve symbol x

Please can anyone let me know why this happen?

Nio Nio
Answer Source

The reason this happens is that although Scala does not require the use of semi-colons most of the time (unlike Java), since the compiler is more equipped to infer where statements/expressions end, if you have 2 statements/expressions on 1 line then you need to separate them for the compiler.

Your first anonymous function works since if(x % 2 == 0) x + 1 else x is 1 expression.

The compiler is complaining with the second one though since if(x % 2 == 0) println(x) is considered 1 statement. Hence, the next statement starts and there is now no context for x.

Other posters have given you a solution to break the right-side of the function down into separate statements so I won't duplicate - just adding an explanation of why the compilation error occurs since you said you are learning the language. Google about the use of semi-colons in Scala to find out more.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download