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
Written by Jeroen Rosenberg
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Scala
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#