[英]Scala type parameter being inferred to tuple
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?
也许这种现象有一个名字?
Here is the excerpt from scala compiler : 以下是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] = ...
And here is related issue: Spec doesn't mention automatic tupling 这里有相关问题:Spec没有提到自动元组
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. 这一切都意味着在上面的编写示例(一个参数的类型参数化方法)中,scala尝试将参数打包到元组中并将函数应用于该元组。 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 .
而这可能被称为自动化 。
% 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.