tags:

views:

152

answers:

2

I have a function like so:

def print(name:String, surname:String) { println(name + " " + surname) }

I also have a Tuple2:

val johnsmith = ("John", "Smith")

When I call print with johnsmith I get the following error:

scala> print(johnsmith)                                                       

error: not enough arguments for method print: (name: String,surname: String)Unit.
Unspecified value parameter surname.
       print(johnsmith)
            ^

Is there some way around this? I can get this to work by making print accept a Tuple2:

def print2(t:Tuple2[String,String]) { println(t._1 + " " + t._2) }

Now I can call it either way:

scala> print2(johnsmith)
John Smith

scala> print2("john", "smith")
john smith

Is there something I'm missing?

+9  A: 

First convert the method to a function, and then convert the function of two args into a function of one tuple.

Function.tupled(print _)(johnsmith)
Dave Griffith
+10  A: 

In addition to Dave's answer, this works too:

(print _).tupled(johnsmith)

Usually, Function.tupled will work best for anonymous functions and closures in combination with map and similar methods. For example:

List("abc", "def", "ghi").zipWithIndex.map(Function.tupled(_ * _))

In this case, the type for _ * _ is already defined by Function.tupled. Try using tupled for that instead and it won't work, because the function is defined before tupled converts it.

For your particular case, tupled works, since the type of print is already known.

Daniel