Question

I have the following code using Dispatch 0.11:

def myHttpPut(urlToPut: String, params: Map[String, String]): Future[Response] = {
  val req = url(urlToPut).PUT
  params.foreach { case (k, v) => req.addParameter(k, v) }
  Http(req)
}

This does not work because addParameter does not modify req - instead it produces a new req object with the parameter added (which, in this case, is being thrown away). What's the most elegant way to write this so that I essentially loop over params, calling addParameter with each key/value pair of the map, building up req until I pass it into Http(req)?

Was it helpful?

Solution

In this case, you want to fold over the params map, applying a function to each key/value pair that also takes the result of calling that function on the previous key/value pair.

val request = params.foldLeft(url(urlToPut).PUT) { case (req, (k, v)) =>
  req.addParameter(k, v)
}
Http(request)

params.foldLeft takes a start value (ur(urlToPut).PUT) and then passes that into the function defined here (case (req, (k, v)) => ...). Each key/value pair in the map gets passed into this function with req taking the value of the previous step (or the start value for the initial step).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top