Scala future not assigned, what’s this doing?

Viewed 160

I’m new to scala and I’m trying to make sense of what this code is doing in a codebase I want to make updates to.

Removing some of the specifics, the chunk I don’t understand is this:

I’ve seen some scala code that does things like:

val someA = something.createSomeA(....)

Future {
      someA.doSomething1(....)
      someA.doSomething2(.....)
}
// then log some things unrelated to the future
someA
// end of func

I don’t really understand what the future is doing in this case as it’s not assigned to anything. Could someone explain what the Future is doing here? I know the details depend on what the doSomethings are actually doing, but could someone explain generally what this would be for? I’m only familiar with the use of Futures when they’re assigned to a variable and then checked for completion in some way at a later point.

Help would be appreciated!! (Sorry for poor formatting, I’m doing this from my phone)

1 Answers

Three words for you: "fire and forget". If you understand the case, when the future is assigned to a variable, and then checked/transformed later, then you already know what's happening here: the insides of the Future are being executed asynchronously.

The only difference is that in this case it is never accessed again. Why? Probably, because nobody cares. Some operations return a result when they complete, that can be used later, others do not.

For example, if I wanted to print out a log message asynchronously, I'd write something like Future { logger.info(mymessage) } without assigning it to anything. Why? Well, I don't really care when (or even if) it completes. There is no return value I could use, and, if it fails ... well, I don't have any meaningful way to handle that, other than ignoring the error.

For an operation like this, I don't need to wait for it to complete, since it doesn't return anything useful back to me anyway. So, I can just start it, and forget. No need to assign it to anything.

Related