I am a beginning practitioner in Scala and I saw a few different syntax for calling a method. Some are nice, as ignoring parenthesis for a parameterless method, or ignoring the dot as in
1 to 10
but some really puzzle me. for instance:
breakable { ... }
this is simply a method call right? Can I also do that for more than one parameter or a parameter which is not a parameterless function?
Thanks
There are two standard ways of calling methods:
The above can be modified in the following ways:
paramsis a single parameter, you can replace()with{}.paramsis a single parameter and you are using operator notation, you can drop the parenthesis.methoddoesn’t take parameters, you can drop(params)(that is, drop the empty()).methodends with:, then it actually binds to the right in operator notation. That is,(params) method_: objis equivalent toobj.method_:(params).obj . method ( params )or write.method(params)on the next line — as often happens with call chaining –, as well as remove spaces from the operator notation, as ina+b.There’s also some stuff with tuple inference, but I try to avoid it, so I’m not sure of the exact rules.
None of these will explain the example you are confused about, however. Before I explain it, however, I’d like to show some syntactic sugars that can also be used to call methods:
Ok, now to the example you gave. One can import members of stable values. Java can do it for static methods with its static import, but Scala has a more general mechanism: importing from packages, objects or common instances is no different: it brings both type members and value members. Methods fall in the latter category.
So, imagine you have
val a = 2, and you doimport a._. That will bring into scope all ofIntmethods, so you can call them directly. You can’t do+(2), because that would be interpreted as a call tounary_+, but you could call*(4), for example:Now, here’s the rule. You can call
If:
methodwas imported into scope.Note that there’s a precedence issue as well. If you write
obj method(params), Scala will presumemethodbelongs toobj, even if it was imported into scope.