在scala中为理解而组成

composed for comprehension in scala

我有一个任务列表供理解:

def main = {
    List("en", "es", "de").foreach(c => execAll(c))
} 

def execAll(country: String): Future[Unit] = {
   for {
      _ <- repo.exec1(country)
      _ <- repo.exec2(country)
      _ <- repo.exec3(country)
      _ <- repo.exec4(country)
      _ <- repo.exec5(country)
   } yield ()
}

现在的问题是因为我只需要为“en”和“es”国家执行函数exec4exec5。 我尝试按条件在期货列表中添加函数(if country == "en" 不要添加它)

val all = for {
      _ <- repo.exec1(country)
      _ <- repo.exec2(country)
      _ <- repo.exec3(country)
} yield ()

val enOrEsOnly = for {
      _ <- repo.exec4(country)
      _ <- repo.exec5(country)
} yield ()

country match {
    case "de" => all
    case other => all + enOrEsOnly // invalid code
}

可以在这里找到使用 for-comprehension 的解决方案吗?还是可以在这里使用期货清单?我不需要他们的结果。谢谢

或者我可以用一个if来解决它:

if (country != "de") {
   repo.exec4(country)
   repo.exec5(country)
}

我宁愿在 repo 上添加一个具有验证的额外层,这样您的代码将是相同的,并且在该额外层中您将执行如下操作:

final class Domain(repo: Repository) {
  def exec4(country: String): Future[Unit] =
    country match {
      case "en" | "es" => repo.exec4(country)
      case _ => Future.unit
    }
}

如何将 execAll 替换为:

def execAll(country: String): Future[Unit] = {
   for {
      _ <- repo.exec1(country)
      _ <- repo.exec2(country)
      _ <- repo.exec3(country)
      if country != "de"
      _ <- repo.exec4(country)
      _ <- repo.exec5(country)
   } yield ()
}