Scala类型参数被推断为元组

时间:2012-10-09 19:25:08

标签: scala syntax

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

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

scala> method(1)
res4: Int = 1

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

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

2 个答案:

答案 0 :(得分:6)

以下是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] = ...

这是related issue: Spec doesn't mention automatic tupling

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

答案 1 :(得分: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)