gpt4 book ai didi

scala - 在 Scala 中将(任一 future 的列表)转换为(任一列表的 future )

转载 作者:行者123 更新时间:2023-12-04 22:39:42 26 4
gpt4 key购买 nike

我在一个宠物 Scala 项目中遇到了一个我真的不知道如何克服的情况。

以下示例显示了我的问题。

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

case class MyBoard(id: Option[Int], name: String)
case class MyList(id: Option[Int], name: String, boardId: Option[Int] = None)
case class ErrorCreatingList(error: String)

def createList(myList: MyList): Future[Either[ErrorCreatingList, MyList]] =
Future {
// Let's close our eyes and pretend I'm calling a service to create this list
Right(myList)
}

def createLists(myLists: List[MyList],
myBoard: MyBoard): Future[Either[ErrorCreatingList, List[MyList]]] = {

val listsWithId: List[Future[scala.Either[ErrorCreatingList, MyList]]] =
myLists.map { myList =>
createList(myList.copy(boardId = myBoard.id))
}

// Meh, return type doesn't match
???
}

我要 createLists返回 Future[Either[ErrorCreatingList, List[MyList]]]但我不知道该怎么做,因为 listsWithId有类型 List[Future[scala.Either[ErrorCreatingList, MyList]]] ,这是有道理的。

有没有办法做到这一点?一位 friend 告诉我“这就是 Cats 的用途”,但它是唯一的选择吗?我的意思是,我不能只使用 Scala 核心库中的内容吗?

谢谢。

最佳答案

使用 Future.sequence在您的 List[Future[???]]使 Future[List[???]]

val listOfFuture: List[Future[???]] = ???

val futureList: Future[List[???]] = Future.sequence(listOfFuture)

关于scala - 在 Scala 中将(任一 future 的列表)转换为(任一列表的 future ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51678775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com