2017-04-01 47 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

相關問題