Scala 的 future inside yield

birdshome 阅读:20 2025-01-19 22:14:33 评论:0

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

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 函数的一行中显示错误:

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

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

最好的问候

请您参考如下方法:

好吧,那么您将从 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 

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


标签:Scala
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号