斯卡拉未来的内部收益率

时间:2016-07-05 11:53:41

标签: scala future

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

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

好的,所以我需要在&#39; case None&#39;中获得此Future的完整结果。我考虑过onComplete函数,但它返回Unit,而不是所需的FightsRow对象。有任何建议如何修复我的功能以获得最佳的可伸缩效果? :)

最好的问候

2 个答案:

答案 0 :(得分:3)

好吧,那么你从createAndFindFight中获得的将是另一个Future。解? flatMap它,但你必须要进行相当多的转换&amp; amp;解开&#39; 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

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

答案 1 :(得分:1)

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