yjlbwq
Last Updated: February 25, 2016
·
5.284K
· jeroenr
Dsc 0061

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

Say Thanks
Respond

2 Responses
Add your response

15078
B2495caca536aa0a730da3f0aeace952

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 ·
24879
2703156

Very cool, much like pythons **kwargs

over 1 year ago ·