【问题标题】:Scala for comprehension how to avoid creating of Future when passing resultsScala 用于理解如何在传递结果时避免创建 Future
【发布时间】:2017-08-07 22:56:09
【问题描述】:

我正在使用 Playframework 和 Slick 异步功能,但不知道如何将 Future 返回方法的结果内联起来以便理解。现在我正在这样做:

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

【问题讨论】:

    标签: scala for-comprehension


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您对完全不使用 yield 有何看法?不确定我是否得到了每个退货声明。

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

      【讨论】:

        猜你喜欢
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 2013-02-15
        • 2017-09-15
        • 2019-02-09
        • 2019-12-27
        • 2019-11-07
        • 1970-01-01
        相关资源
        最近更新 更多