Scala 用于理解如何在传递结果时避免创建 Future

Scala for comprehension how to avoid creating of Future when passing results

我正在使用 Playframework 和 Slick 异步功能,但不确定如何将 Future returning 方法的结果内联到一个中以便理解。现在我是这样做的:

def getWordDefinitions(checkedWordsIds: List[CheckedWord]) : Future[List[WordDefinition]] = {
  val ids = checkedWordsIds.map(_.wordId)

  for {
    translations <- translationRepo.findByIds(ids)
    translations2 <- Future(sortByHowManyChecks(checkedWordsIds, translations))
    wordDefinitionsList <- Future(translations2.map(translation => WordDefinition(translation._2.english, translation._2.translation)))
  } yield {
    wordDefinitionsList
  }
}

我想知道如何摆脱 translations2 <- Future(),除了将其移动到函数中(或将函数包装到另一个 return Future 中)。 sortByHowManyChecks 函数 returns Map[Long, TranslationObject] 位于第 3 方库中。

在你的情况下,你可以简单地这样写:

def getWordDefinitions(checkedWordsIds: List[CheckedWord]) : Future[List[WordDefinition]] = {
  val ids = checkedWordsIds.map(_.wordId)

  for {
    translations <- translationRepo.findByIds(ids)
    translations2 = sortByHowManyChecks(checkedWordsIds, translations)
  } yield translations2.map(translation => WordDefinition(translation._2.english, translation._2.translation))
}

对于完全不使用 yield,您怎么看?不确定我是否每个 return 陈述都正确。

def getWordDefinitions(checkedWordsIds: List[CheckedWord]) : Future[List[WordDefinition]] = {
  val ids = checkedWordsIds.map(_.wordId)

  translationRepo.findByIds(ids)
    .map(translations => sortByHowManyChecks(checkedWordsIds, translations))
    .map(translation => WordDefinition(translation._2.english, translation._2.translation))
}