0
     for {
        Some(article) <- articleService.get(id) // returns Future[Option[Article]]
        Some(account) <- accountService.get(article.authorId) // resturns Future[Option[Account]]
      } yield ArticleDetail(article, account)

This way is pretty straight forward but not safe, because the Some(article) and Some(account) may throw NoSuchElementException

Of course we can use flatMap to rewrite it like this

articleService.get(id).flatMap {
  case Some(article) => accountService.get(article.authorId).map(ArticleDetail(article, _))
  case None =>
    Future.successful(None)
}

But not so straight forward

Is there a safe and simple way to do this ?

jilen
  • 5,633
  • 3
  • 35
  • 84

0 Answers0