How to cleanly deal with nested Future[Option[A]]

Viewed 44

I think this is probably a simple question, but I'm really struggling to get it right, I have the following functions:

def getInfo(identifier: Int): Future[Option[Info]]

def deleteInfo(info: Info): Future[Bool]

I'm trying to implement the following:

def deleteInfoByID(identifier: Int): Future[Bool]

I'm wondering what the cleanest way to do this is? I've tried a few variations on map and flatMap, but I can't seem to propagate the result of deleteInfo back to the top:

def deleteInfoByID(identifier: Int): Future[Bool]
    getInfo(identifier).map { infoOpt: Option[Info] =>
      infoOpt.map { info =>
        deleteInfoByID(identifier)
      }
    }
2 Answers

You should rather flatMap:

def deleteInfoByID(identifier: Int): Future[Bool]
  getInfo(identifier).flatMap {
    case Some(id) => deleteInfoByID(id)
    case _ => Future.successful(false)
  }

I'm a fan of fold().

def deleteInfoByID(identifier: Int): Future[Boolean] =
  getInfo(identifier)
    .flatMap(_.fold(Future.successful(false))(deleteInfo))
Related