Blankman
Blankman

Reputation: 267120

Passing in a Int value that comes from a Option Future

I have a method I am struggling with that has a Option[Future[User]].

def insertEmployee(userOpt: Option[User], ...): Future[...] = {

  val userOptFut: Option[Future[User]] = userOpt.map { user => 
    userDao.insert(....) // returns a Future[User]
  }

  for {
    employee <- employeeDao.insert( Employee(..., ??, ......) )
  } yield ...

}

Now the issue I am having is that Employee case class takes an optional UserId value:

case class Employee(..., userId: Option[Int], ...)

How do I pass the user.id value to the Employee case class if it is present?

Upvotes: 0

Views: 256

Answers (2)

Andrei T.
Andrei T.

Reputation: 2480

You can do a small trick with the Option[Future[Int]]:

for {
  List(user) <- Future.sequence(userOptFut)
  employee   <- employeeDao.insert(Employee(..., user.id, ...))
}

Upvotes: 1

Tyler
Tyler

Reputation: 18177

You will need a little bit of logic to transform your types into the things you want:

val userOptFut: Option[Future[User]] = ???

// Convert the Option[Future[User]] to a Option[Future[Int]]
val maybeFutureID = userOptFut.map(_.map(_.id))

// Convert the Option[Future[Int]] to a Future[Option[Int]]
val futureOptionID = maybeFutureID match {
  case None => Future.successful(Option.empty[Int])
  case Some(futureID) => futureID.map(id => Some(id))
}

for {

  // Wait for Future[Option[Int]]
  maybeID <- futureOptionID

  // Insert employee
  employee <- employeeDao.insert(Employee(..., maybeID, ...))
} yield ...

Upvotes: 1

Related Questions