//Imagine we don't want to try to store nulls or empty strings
//Returns a Future[Unit] which will be completed once the operation has completed
defstoreInDB(s:String):Future[Unit]=smatch{casenull|""=>Future.unitcaseother=>db.store(s)}valf:Future[String]=…valf2=fflatMapstoreInDB

Another important scenario, which wasn’t really readily solvable unless you were comfortable with implementing it yourself was a Future which would never complete.

Now, the naïve implemention of said Future would look something like:

valneverCompletingFuture:Future[Nothing]=Promise[Nothing].future

Take a few seconds to think about the following question: In what ways would that solution be undesirable?

…

…

…

…

Hint: What happens with logic which gets added to neverCompletingFuture?
Example:

Well, what happens is that the logic is packaged and added to the neverCompletingFuture instance in order to be executed when neverCompletingFuture completes (which is never), and now we have a hard to spot invisible memory leak!

So, in order to support the case when you want to be able to represent a Future which never completes, but also doesn’t leak memory when used as a plain Future, use Future.never.

An example use-case might be when you need to pass in a Future which should not affect the outcome, as in:

valsomeImportantFuture:Future[String]=…valsomeLessImportantFuture:Future[String]=if(someCondition)Future.neverelseFuture.successful("pigdog")// Will always pick someImportantFuture if someCondition is true
valfirst=Future.firstCompletedOf(someImportantFuture,someLessImportantFuture)

Benefits:

Future.unit is a «zero» instance which is cached

Future.never removes the risk of memory leaks when used as a Future instance which never completes