Scala Option[Future[T]] to Future[Option[T]]

Michał Jurczuk picture Michał Jurczuk · Jul 6, 2016 · Viewed 14k times · Source

How can I convert Option[Future[T]] to Future[Option[T]] in scala?

I want to use it in:

val customerAddresses = for {
  a <- addressDAO.insert(ca.address) // Future[Address]
  ia <- ca.invoiceAddress.map(addressDAO.insert) // Option[Future[Address]]
} yield (a, ia) // Invalid value have to be two futures

Here signature insert method

def insert(address: Address): Future[Address]

ca is a CustomerData

case class CustomerData(address: Address, invoiceAddress: Option[Address])

Answer

Kevin Meredith picture Kevin Meredith · Jul 6, 2016
import scala.concurrent.Future
import scala.concurrent.ExecutionContext

def f[A](x: Option[Future[A]])(implicit ec: ExecutionContext): Future[Option[A]] = 
  x match {
     case Some(f) => f.map(Some(_))
     case None    => Future.successful(None)
  }

Examples:

scala> f[Int](Some(Future.successful(42)))
res3: scala.concurrent.Future[Option[Int]] = Success(Some(42))

scala> f[Int](None)
res4: scala.concurrent.Future[Option[Int]] = scala.concurrent.impl.Promise$KeptPromise@c88a337