Search code examples
scalafor-comprehension

return future from onComplete scala


An exercise on forComprehension, doesn't compile since returns Unit instead of Future[User]

(the task is to read using DAO and create new user using 2 parents)

I'm trying to return Future[User] from onComplete but fails (returns Unit).

def unbornUsingForComp(fatherId: String, motherId: String): Future[User] = {

  val fatherUser: Future[Option[User]] = usersDao.read(fatherId)
  val motherUser: Future[Option[User]] = usersDao.read(motherId)

  val combinedLastName = for {
    r1 <- fatherUser
    r2 <- motherUser
  } yield (r1, r2)

  combinedLastName.onComplete {
    case Success(x) => {
      (x._1, x._2) match {
        case (Some(u1), Some(u2)) => usersDao.create(User("JustRandomId", "JustRandomFirstName", u1.lastName + " - " +u2.lastName))
        case _ => throw new Exception("One or more of the parents not Found")
      }
    }
    case Failure(_) => {
      throw new Exception("Exception raised inside the for comp.")
    }
  }
}

Solution

  • onComplete by design returns Unit which executes a side-effect and then discards

    // Note that the returned value of `f` will be discarded.
    def onComplete[U](f: Try[T] => U)(implicit executor: ExecutionContext): Unit
    

    You are likely after something like

    combinedLastName
      .map { x => // do stuff with x }
      .recover { case e => // handle exception }