val svc = url("http://api.hostip.info/country.php")
val country = Http(svc OK as.String)
The above defines and initiates a request to the given host where 2xx responses are handled as a string. Since Dispatch is fully asynchronous, country represents a future of the string rather than the string itself.
You can act on the response once it’s available with a for-expression.
for (c <- country)
println(c)
This for-expression applies to any successful response that is eventually produced. If no successful response is produced, nothing is printed. This is how for-expressions work in general. Consider a more familiar example:
val opt: Option[String] = None
for (o <- opt)
println(o)
An option may or may not contain a value, just like a future may or may not produce a successful response. But while any given option already knows what it is, a future may not. So the future behaves asynchronously in for-expressions, to avoid holding up operations subsequent that do not depend on its value.
A future is like an option that doesn’t know what it is yet; that doesn’t stop it from transforming into something else. We could transform an option of a string into an option of its length. Same goes for futures.
import dispatch._, Defaults._
val svc = url("http://api.hostip.info/country.php")