Why and how is Scala treating a tuple specially when calling a one arg function?

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.

Leave a Comment