Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a function that takes 2 parameters with a Tuple2?

Tags:

tuples

scala

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?

like image 265
ssanj Avatar asked Aug 18 '10 02:08

ssanj


2 Answers

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.

like image 192
Daniel C. Sobral Avatar answered Oct 27 '22 09:10

Daniel C. Sobral


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)
like image 22
Dave Griffith Avatar answered Oct 27 '22 10:10

Dave Griffith