如何使用遍历生成效果列表

问题描述 投票:0回答:1

我有这样的功能:

 def getFile(url: String): EitherT[Future, Error, ByteString]

这正在使用猫EitherT。

我使用另一个这样的函数来调用此函数:

def getAllFiles(urls: List[String]): EitherT[Future, Error, List[ByteString]] = {
    urls.map(f => getFile(f).value)
  }

这在我输入类型不匹配时不起作用:

found   : List[scala.concurrent.Future[Either[Error,akka.util.ByteString]]]
[error]  required: cats.data.EitherT[scala.concurrent.Future,Error,List[akka.util.ByteString]]

无论我尝试什么,都无法编译。基本上我想做的是为每个URL运行getFile并以Bytestring下载文件。

scala scala-cats
1个回答
0
投票

此作品:

import cats.data.EitherT
import cats.effect.IO
import cats.implicits._

type Error = String
type ByteString = Array[Byte]

def getFile(url: String): EitherT[IO, Error, ByteString] = ???

def getAllFiles(urls: List[String]): EitherT[IO, Error, List[ByteString]] =
  urls.traverse(getFile)

但这不是:

def getFile(url: String): EitherT[Future, Error, ByteString] = ???

def getAllFiles(urls: List[String]): EitherT[Future, Error, List[ByteString]] =
  urls.traverse(getFile)

原因是traverse从嵌套效果中期望Applicative,而catsIO提供了,但没有为Future提供。

© www.soinside.com 2019 - 2024. All rights reserved.