Scala_PlayFramework _Map


#1

how to use .map method in play framework


#2

On what class or object are you calling the map method?


#3

on Future Object returned by flatMap


#4

So, the easiest way to think about Future[T] is as “a box that should eventually contain a value of type T”.

Looking at it that way, Future.map() is saying “what should we do once we do have a T”. Specifically, what you put inside the map() function should be a transformation – taking the T, and turning it into the U that you actually want.

So for example, say that you have a function def fetchUser(userId: String): Future[User] – it takes the userId and eventually will return the User, having looked it up in a database or some such. You would then typically use that to render a page, sort of like this:

fetchUser(userId).map { user =>
  Ok(view.html.welcomePage(user))
}

The parameter of Future[User].map() is a function that takes a User and returns something based on that user – in this case, the web page. So when the Future is ready – once we have the User and have put it into the box – this function will be called, passing in the User and returning the rendered page using it.

Programming with Futures is all about constructing chains of map() and flatMap(), each one transforming the results until you wind up with a Future[Z], where Z is the type you actually want at the end. (Generally a rendered page in the case of Play.) Play is smart about Futures, so that you can describe your action using Action.async, and just return that Future[Z], and Play will handle that correctly…