Scala类型参数被推断为元组

dmi*_*try 12 syntax scala

我突然遇到了这个(意想不到的)情况:

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

scala> method(1)
res4: Int = 1

scala> method(1, 2)
res5: (Int, Int) = (1,2)
Run Code Online (Sandbox Code Playgroud)

为什么在两个或更多参数方法的情况下返回并推断出一个元组但是抛出关于参数列表的错误?是故意吗?也许这种现象有一个名字?

dmi*_*try 6

以下是scala编译器的摘录:

/** 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] = ...
Run Code Online (Sandbox Code Playgroud)

这里有相关问题:Spec没有提到自动元组

这一切都意味着在上面的编写示例(一个参数的类型参数化方法)中,scala尝试将参数打包到元组中并将函数应用于该元组.从这两条简短的信息中我们可以得出结论,这种行为在语言规范中没有提到,人们讨论为自动元组添加编译器警告.而这可能被称为自动化.


psp*_*psp 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)
Run Code Online (Sandbox Code Playgroud)