Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type parameter being inferred to tuple

Tags:

syntax

scala

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?

like image 724
dmitry Avatar asked Oct 09 '12 19:10

dmitry


2 Answers

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.

like image 69
dmitry Avatar answered Sep 30 '22 22:09

dmitry


% 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)
like image 37
psp Avatar answered Oct 01 '22 00:10

psp