E.g. If I write this function:
def function1() : Unit = {
aVar = myList.map { ( s :Something ) => (s.id, s.name) } toList
function2()
}
def function2() : Unit = {
//bla
}
The compiler complains when calling function2 saying expecting Int but found Unit. I just can’t figure out where the required Int comes from.
Now, if I write function1 as follows it compiles and works exactly as I was expecting:
def function1() : Unit = {
aVar = myList.map { ( s :Something ) => (s.id, s.name) } toList
var x = function2()
}
Why!!!!???? Just assigning function2 to a var changes the behavior?? In first place function2 is defined to return Unit…
Next it gets more tangled, any of the next two function1 definitions works perfectly:
def function1() : Unit = {
aVar = myList.map { ( s :Something ) => (s.id, s.name) }.toList
function2()
}
def function1() : Unit = {
aVar = (myList.map { ( s :Something ) => (s.id, s.name) } toList)
function2()
}
It looks like having an space instead a dot sometimes can be dangerous but I can’t figure out why.
Using space instead of
.in scala should be used preferably with one parameter function in the following way:Thus, when you type myMap
toList, the compiler still waiting for a param, and take it from the next line of code, while, when you typemyMap.toListit doesn’t wait for anything and it considers function2 as a independent instruction.It’s quite the same when you assign the result of
function2to avar. As soon as the compiler see thevardeclaration, it understands that the previous statement is closed and don’t expect a parameter anymore.Here, you should wonder what parameter does the compiler expect, as
toListdoesn’t need any. Actually,toListreturns aListandListhas anapplymethod… And that’s exactly what the compiler is waiting for: the parameter ofList‘s apply method.Maybe this REPL session will help you: