2017-04-01 163 views
1

有人可以解释为什么下面的代码编译?传递非元组到(Int,Int)=>()编译,为什么?

我认为它不应该编译。

object RandomExperiments extends App{ 
    def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n") 
    takeTuple(1,3) // this should not compile !!! 
    takeTuple (1,3) // this should not compile !!! 
    takeTuple((1,3)) 
    takeTuple(((1,3))) 

    def takeTwoInts(i1:Int,i2:Int)=print (s"$i1 $i2\n") 

    takeTwoInts(1,2) 

    // takeTwoInts((1,2)) // does not compile , this is expected 

} 

(1,3) 1 
(1,3) 1 
(1,3) 1 
(1,3) 1 
1 2 
+1

这是Scala的自动几倍的“功能”。请参阅例如我的回答[此处](http://stackoverflow.com/a/42730285/334519)以进行一些讨论,并提供一个选项,您至少可以启用此结果以进行警告。 –

+0

请参阅http://stackoverflow.com/questions/12806982/scala-type-parameter-being-inferred-to-tuple – Eric

+0

谢谢,有趣的知道。 – jhegedus

回答

8

它被称为auto-tupling。编译器发现没有可用于takeTuple的过载,该过载有两个Int参数,但认识到如果参数可以转换为(Int, Int)并进行转换。如果您有-Xlint:_编译,你会看到一个警告是这样的:

scala> takeTuple(1,3) 
<console>:12: warning: Adapting argument list by creating a 2-tuple: this may not be what you want. 
     signature: takeTuple(t: (Int, Int)): Unit 
    given arguments: 1, 3 
after adaptation: takeTuple((1, 3): (Int, Int)) 
     takeTuple(1,3) 
       ^

您可以使用-Yno-adapted-args标志(推荐)禁用此功能

+0

感谢您的回答! – jhegedus

相关问题