Last Updated: February 25, 2016
·
10.51K
· Jeroen Rosenberg

Scala map to tuples or splat operator

A couple of times I found myself in the situation of needing to pass in a Map, like:

Map("Content-Type" -> "application/json", "Content-Length" -> "200")

to a variadic function which only accepts tuples, like:

def withHeaders(headers: (String, String)*) = {
    ...
}

Googling for 'Scala map to tuples' or 'Scala splat operator' didn't give me much, so I figured out this little trick and wanted to share it:

val m = Map("Content-Type" -> "application/json", "Content-Length" -> "200")
withHeaders(m.toSeq: _*)

m.toSeq results in a Seq[(String,String)] and appending :_* to it will make the compiler perform the splat

2 Responses
Add your response

Hahaha really funny I encountered the same problem with Play response ;)

map { result =>
val originToAllow = request.headers.get("Origin").getOrElse("")
val newHeaders: Map[String, String] = result.header.headers + ("Access-Control-Allow-Origin" -> originToAllow)
result.withHeaders(newHeaders.toSeq: _
)
}

over 1 year ago ·

Very cool, much like pythons **kwargs

over 1 year ago ·