1

Can someone explain why the code below compiles ?

I think it should not compile.

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
jhegedus
  • 20,244
  • 16
  • 99
  • 167
  • 1
    This is Scala's auto-tupling "feature". See e.g my answer [here](http://stackoverflow.com/a/42730285/334519) for some discussion and an option you can enable to make this result in warnings, at least. – Travis Brown Apr 01 '17 at 21:01
  • See http://stackoverflow.com/questions/12806982/scala-type-parameter-being-inferred-to-tuple – Eric Apr 01 '17 at 21:01
  • Thanks, interesting to know. – jhegedus Apr 02 '17 at 08:44

1 Answers1

8

It's known as auto-tupling. The compiler sees that there is no overload available for takeTuple that has two Int arguments, but recognizes that if the arguments can be converted to an (Int, Int) and makes the conversion. If you compile with -Xlint:_, you will see a warning like this:

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)
                ^

You could use the -Yno-adapted-args flag (recommended) to disable this feature

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138