【问题标题】:Scala's future inside yieldScala 的未来内部收益
【发布时间】:2016-11-07 06:04:12
【问题描述】:

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

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 函数返回 Future[Option[FightsRow]] 对象,createAndFindFight 函数返回 Future[FightsRow]。现在编译器在 createAndFindFight 函数的一行中显示错误:

类型不匹配;成立 : scala.concurrent.Future[models.Tables.FightsRow] 需要: models.Tables.FightsRow

好的,所以我需要在“无”的情况下得到这个 Future 的完整结果。我考虑过 onComplete 函数,但它返回 Unit,而不是所需的 FightsRow 对象。任何建议如何修复我的功能以获得最佳的可扩展效果? :)

最好的问候

【问题讨论】:

    标签: scala future


    【解决方案1】:

    好的,所以您将从createAndFindFight 中得到另一个Future。解决方案? flatMap 它,但您必须将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
    

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

    【讨论】:

    • 有效!非常感谢您的建议! :)
    【解决方案2】:

    我对 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)
      }
    

    【讨论】:

    • @Gandalf 您的下一步是为有用的答案投票并接受最佳答案。
    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多