Scala-如何在foreach理解块中使用foreach循环? [英] Scala - how to use foreach loop in for comprehension block?

查看:596
本文介绍了Scala-如何在foreach理解块中使用foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码:

 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)

此代码从github返回存储库列表和贡献列表.但是现在我需要为createReposList找到的每个存储库调用createContributorsList.我已经完成了for comprehension块:

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

工作正常,它找到了给定组织(github)的存储库.所以我尝试这样做:

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)

但是list始终为空.我不知道没有for comprehension怎么办,因为我在Monads上像IO一样在这里进行操作.我应该如何创建代码来遍历repos的每个回购并在所有人身上调用stats.createContributorsList?

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?

推荐答案

尝试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返回Unit,所以这不是您所需要的.

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

这篇关于Scala-如何在foreach理解块中使用foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆