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

标签 scala monads future

我在一个宠物 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/

相关文章:

haskell - 无限循环与IO如何在haskell中工作

haskell - 非详尽模式异常,用于绑定(bind)但不用于 do

concurrency - rust future -cpupool : inconsistent behavior explanations

java - Callable 执行期间出现异常

dart - Flutter future 如何重跑?

scala - 前向引用 - 为什么这段代码可以编译?

scala - Scala 有 0 元组和 1 元组的语法吗?

维基百科上的 Scala 闭包

scala - spark 中的自定义输入阅读器

haskell - 为什么 State 需要一个值?