SkyWalker
SkyWalker

Reputation: 14309

Scala how to convert Map to varargs of tuples?

In the context of Scala Play 2.2.x testing I have a Map[String, String] which I need to pass to a function that accepts (String, String)* i.e. a varargs of (String, String) tuple.

e.g.

val data : Map[String, String] = Map("value" -> "25", "id" -> "", "columnName" -> "trades")
route(FakeRequest(POST, "/whatever/do").withFormUrlEncodedBody(data))

but this gives a type mismatch because withFormUrlEncodedBody accepts only a (String, String)* type.

Upvotes: 3

Views: 1866

Answers (2)

om-nom-nom
om-nom-nom

Reputation: 62835

Simply:

def foo(names: (String, String)*) = names.foreach(println)
val folks = Map("john" -> "smith", "queen" -> "mary")
foo(folks.toSeq:_*)
// (john,smith)
// (queen,mary)

Where _* is a hint to compiler.

Upvotes: 8

SkyWalker
SkyWalker

Reputation: 14309

Oh found the answer e.g.

route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toList: _*))

or

route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toSeq: _*))

or

route(FakeRequest(POST, "/wharever/do").withFormUrlEncodedBody(data.toArray: _*))

Upvotes: 3

Related Questions