Search code examples
scalafor-comprehension

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


I'm using Playframework and Slick async features, but not sure how to work inline with results from Future returning method in one for comprehension. Right now I'm doing it such way:

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

I want to know how to get rid off translations2 <- Future(), besides move it to the function (or wrap function into another which return Future). sortByHowManyChecks function returns Map[Long, TranslationObject] which is in 3rd party library.


Solution

  • In your case you can simply write it this way:

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