处理Futures时如何处理for-comp中的可选值

时间:2017-04-06 16:27:45

标签: scala

我有一个compr,看起来像:

for {
  user <- getFutureUser(1) // Future[User]
  account <- getFutureAccount(1) // Future[Account]
  historyOpt <- ???
 } yield Wrapper(user, account, historyOpt)

case class Wrapper(user: User, account: Account, historyOpt: Option[History])

我被困在如何处理historyOpt值。 我有一种获取历史的方法:

def getHistory(id: Int): Future[History]

但这是基于用户的,如果user.getHistory为true,则返回,否则为None。

我试过这个但是错了:

for {
  user <- getFutureUser(1) // Future[User]
  account <- getFutureAccount(1) // Future[Account]
  historyOpt <- if(user.getHistory) getFutureHistory(1) else Future.successful(None)
 } yield Wrapper(user, account, historyOpt)

如何处理此场景?

1 个答案:

答案 0 :(得分:1)

快速回答:

case class User(getHistory: Boolean)
case class Account()
case class History()

def getFutureUser(x: Int): Future[User] = ???
def getFutureAccount(x: Int): Future[Account] = ???
def getFutureHistory(x: Int): Future[History] = ???

case class Wrapper(user: User, account: Account, historyOpt: Option[History])

val a: Future[Wrapper] = for {
  user <- getFutureUser(1) // Future[User]
  account <- getFutureAccount(1) // Future[Account]
  historyOpt <- if(user.getHistory) getFutureHistory(1).map(Some.apply) else Future.successful(None)
} yield Wrapper(user, account, historyOpt)