Scala 的未来 inside yield

Scala's future inside yield

我想在数据库中找到一些对象(战斗),并根据它的存在 return 这个特定对象或在数据库中创建一个新对象和 return 新创建的对象。我实现了以下功能:

def findOrCreateFight(firstBoxer: BoxersRow, secondBoxer: BoxersRow, eventDate: java.sql.Date): Future[FightsRow] = {
  for {
    fight <- findByBoxersAndDate(firstBoxer, secondBoxer, eventDate)
  } yield {
    fight match {
      case Some(f) => f
      case None => createAndFindFight(firstBoxer, secondBoxer, eventDate)
    }
  }
}

findByBoxersAndDate 函数 returns Future[Option[FightsRow]] 对象和 createAndFindFight 函数 returns Future[FightsRow]。现在编译器在 createAndFindFight 函数的一行中显示错误:

type mismatch; found : scala.concurrent.Future[models.Tables.FightsRow] required: models.Tables.FightsRow

好的,所以我需要在 'case None' 中得到这个 Future 的完成结果。我考虑过 onComplete 函数,但它 returns Unit,而不是所需的 FightsRow 对象。关于如何修复我的功能以获得最佳可扩展效果的任何建议? :)

此致

好的,那么您将从 createAndFindFight 中得到的将是另一个 Future。解决方案? flatMap 它,但是你几乎必须 'convert & unwrap' Option 来适当地输入:

findByBoxersAndDate(firstBoxer, secondBoxer, eventDate)
    .flatMap(_.map(Future.successful).getOrElse(createAndFindFight(firstBoxer, secondBoxer, eventDate)))

或者,直接匹配你的理解:

for {
  potentialFight <- findByBoxersAndDate(firstBoxer, secondBoxer, eventDate)
  actualFight <- potentialFight match {
      case Some(f) => Future.successful(f)
      case None => createAndFindFight(firstBoxer, secondBoxer, eventDate)
  }
} yield actualFight

免责声明:以上代码未经测试:)

我对 Patryk Ćwiek 想法进行了小的改进:

def findOrCreateFight(first: BoxersRow, second: BoxersRow, date: java.sql.Date): Future[FightsRow] =
  findByBoxersAndDate(first, second, date).flatMap {
    case None => createAndFindFight(first, second, date)
    case Some(row) => Future.successful(row)
  }