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

scala, tuples

Solution

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.

Problem

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 ``` scala> println(1, 2) (1,2) ``` The answer says that the compiler allows one arg functions to be called with no parens, so that logically this is a call to println with a tuple. But println cannot be called with a single tuple parameter ``` scala> val t = (1, 2) t: (Int, Int) = (1,2) scala> println t <console>:6: error: value t is not a member of Unit println t ^ ``` so something else is going on. Why are tuples special here?

Original source

Related problems