Skip to content

Instantly share code, notes, and snippets.

@akimboyko
Created December 5, 2013 04:23
Show Gist options
  • Select an option

  • Save akimboyko/7800039 to your computer and use it in GitHub Desktop.

Select an option

Save akimboyko/7800039 to your computer and use it in GitHub Desktop.
Why is Future.always useful? Why would I use it if its value is already precomputed?

Future.always is a way to lift a normal value T to a Future[T] value. This lifting pattern is something you will see often in functional programming, so remember it well!

To make its usefulness more apparent - imagine that your API method should either call some Web service or look in the cached responses to see if the Web service was already queried with that request. In the first case you have to return a future Future[String] of a response, and in the second you need to return a response String right away from your cache. Future.always can help you solve this tricky type situation.

def query(request: String): Future[String] =
if (cache.contains(request)) Future.always(cache(request))
else Future { askServer(request) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment