scala coalesces multiple function call parameters into a Tuple -- can this be disabled? discusses Scala creating a tuple to bind to one arg function. This results in
<A statement, that you can omit parens when calling on-arg function is not always true. Note, that:
println "hello"
val puts = (s: String) => println(s)
puts "hello"
don't work either, despite that there's no tuple here. It works if you use infix notation. Following statements work great:
Console println "hello"
val t = (1, 2)
Console println t
puts apply "hello" // puts is defined above
Contrary to this explanation, Scala parses println(1,2)
(or Console println (1,2)
for that matter) the same way it parses any two-argument method call. Later, the compiler transforms the call by wrapping the method arguments in a tuple to match the actual method type signature.
If the compiler did not do this, perfectly valid expressions like Console println (1,2)
would fail to compile because println
does not take multiple arguments. There are also other valid use cases for this behavior.
Consider an expression like foo bar (1,2)
from the compiler's point of view, keeping in mind that Scala has special syntax that allows you to drop the .
and the parens on method calls. This could be a call to a two-argument bar
method with arguments 1
and 2
, or it could be a call to a one-argument bar
method with a single tuple-valued argument. The parser doesn't know anything about the bar
method, so it just parses as a two-argument method call.
During the type checking phase, suppose the compiler determines that foo
has no two-argument bar
method but that it does have a one-argument bar
method whose signature is compatible with the tuple interpretation. Since there is no other valid interpretation, it assumes that this is what you meant and transforms the two arguments into a tuple. Note that if there is a two-argument bar
method, even one that is incompatible with the actual arguments, the typer will not perform the auto-tupling transformation.