

You handle the result of a future with callback methods like onComplete and andThen, or transformation methods like filter, map, etc.


To demonstrate how this works, let’s start with a Future example in the REPL.įirst, paste in these required import statements: An example in the REPLĪ future is used to create a temporary pocket of concurrency.įor instance, you use a future when you need to call an algorithm that runs an indeterminate amount of time-such as calling a remote microservice-so you want to run it off of the main thread. While an actor may live forever, a future eventually contains the result When you think about futures, it’s important to know that they’re intended as a one-shot, “Handle this relatively slow computation on some other thread, and call me back with a result when you’re done” construct.Īs a point of contrast, Akka actors are intended to run for a long time and respond to many requests during their lifetime. You’ll also see examples of methods that are used to handle the value in a future once it returns.
#Scala foreach how to#
In this chapter you’ll see how to use futures, including how to run multiple futures in parallel and combine their results in a for expression. sleep ( 500 ) 42 val x = aShortRunningTask () println ( "Here" )Ĭonversely, if aShortRunningTask is created as a Future, the println statement is printed almost immediately because aShortRunningTask is spawned off on some other thread-it doesn’t block.

You will continue to think imperatively, that is, “do this, do that, increment this, and as long as y < 42, just increment y”.Def aShortRunningTask () : Int = Thread. If loops are one of the first things you learn in Scala, that will validate all the other concepts you might have encountered in other languages. It’s as if you wanted to learn French but still pronounce the ‘h’. Learning loops to get familiar with Scala is bad. What I actually got: What should we use instead? If you don’t want us to use them, why are you showing us this? What I was expecting from the audience: “OK, we’ve wiped my memory clean and fresh. I even continued further: “I’ve just shown you loops so that you can relate to them, but please don’t use them.”. For a long time, I’ve been guilty of this myself. People look confused, so the instructor continues: “Just trust me.”. values are constants val x = 3 // variables are changeable, much like any other language var y = 4 y = 5 // reassignment ok // looping while ( y < 42 ) Īfter that, the instructor usually says: “Cool, now that you’ve learned about while, please don’t use them.
