Scala - how to use foreach loop in for comprehension block?

走远了吗. 提交于 2019-12-04 06:08:41

问题


I have a simple code:

 override def createContributorsList(url: String, params: String): F[List[Contributor]] = getContributorsFromClient(url, params).fold[List[Contributor]](_ => List(), res => res)

 override def createReposList(organization: String, params: String): F[List[GitRepository]] = getReposFromClient(organization, params).fold[List[GitRepository]](_ => List(), res => res)

This code return list of repositories from github and list of contributions. But now I need to call createContributorsList for every repository I found by createReposList. I have done a for comprehension block:

val stats = new StatisticsRepository[IO](new GitHttpClient[IO])
val res = for {
    repos <- stats.createReposList("github", "")
  } yield repos

It works fine, it found repositories for given organization (github). So I tried do it like this:

val res = for {
    repos <- stats.createReposList("github", "")
    list = repos.foreach(repo => stats.createContributorsList(repo.contributors_url, ""))
  } yield (repos, list)

But list is always empty. I don't know how I could do this without for comprehension, because I operate here on Monads like IO. How I should create a code to loop over every repo from repos and call stats.createContributorsList on everyone?


回答1:


Try flatTraverse

import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.syntax.traverse._
import cats.instances.list._

val res: F[(List[GitRepository], List[Contributor])] = for {
  repos <- stats.createReposList("github", "")
  list <- repos.flatTraverse(repo => stats.createContributorsList(repo.contributors_url, ""))
} yield (repos, list)

foreach return Unit so that's not what you need.



来源:https://stackoverflow.com/questions/58793071/scala-how-to-use-foreach-loop-in-for-comprehension-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!