12

I suddenly came across this (unexpected to me) situation:

def method[T](x: T): T = x

scala> method(1)
res4: Int = 1

scala> method(1, 2)
res5: (Int, Int) = (1,2)

Why in case of two and more parameters method returns and infers a tuple but throwing error about parameter list? Is it by intention? Maybe this phenomenon has a name?

dmitry
  • 4,989
  • 5
  • 48
  • 72
  • ok, I know the answer already, but want to give accept to someone else :) Will wait – dmitry Oct 09 '12 at 19:44
  • 7
    answer a question by oneself is encouraged by SO, so do it... – kiritsuku Oct 09 '12 at 19:56
  • Yes, I'd like to know too. Feel free to answer the question yourself! – Lukas Eder Oct 09 '12 at 20:05
  • It seems like there are a [lot](http://stackoverflow.com/questions/5997553/why-and-how-is-scala-treating-a-tuple-specially-when-calling-a-one-arg-function) of [questions](http://stackoverflow.com/questions/2850902/scala-coalesces-multiple-function-call-parameters-into-a-tuple-can-this-be-di) that are related. – Dave L. Oct 09 '12 at 20:17
  • in case if someone misunderstood my first comment ("ok, I know the answer") - I hadn't known it when I was writing question. It is just a coincidence that I found answer in anoother source. Of course I ask question not as a test to show what tricky questions I can produce. – dmitry Oct 09 '12 at 20:48

2 Answers2

6

Here is the excerpt from scala compiler:

/** Try packing all arguments into a Tuple and apply `fun'
 *  to that. This is the last thing which is tried (after
 *  default arguments)
 */
def tryTupleApply: Option[Tree] = ...

And here is related issue: Spec doesn't mention automatic tupling

It all means that in the above written example (type-parameterized method of one argument) scala tries to pack parameters into tuple and apply function to that tuple. Further from this two short pieces of information we may conclude that this behaviour not mentioned in language specification, and people discuss to add compiler warnings for cases of auto-tupling. And that this may be called auto-tupling.

dmitry
  • 4,989
  • 5
  • 48
  • 72
  • Here http://stackoverflow.com/a/2851212/978664 written that it is some parser quirk, but I think they were discussing some similar but another case. – dmitry Oct 09 '12 at 20:55
3
% scala2.10 -Xlint

scala> def method[T](x: T): T = x
method: [T](x: T)T

scala> method(1)
res1: Int = 1

scala> method(1, 2)
<console>:9: warning: Adapting argument list by creating a 2-tuple: this may not be what you want.
        signature: method[T](x: T): T
  given arguments: 1, 2
 after adaptation: method((1, 2): (Int, Int))
              method(1, 2)
                    ^
res2: (Int, Int) = (1,2)
psp
  • 12,138
  • 1
  • 41
  • 51