在Scala中将(任一个的未来列表)转换为(列表中的任一个的未来)
发布时间:2020-12-16 09:52:06 所属栏目:安全 来源:网络整理
导读:我有一个宠物 Scala项目的情况,我真的不知道如何克服. 以下示例显示了我的问题. import scala.concurrent.Futureimport scala.concurrent.ExecutionContext.Implicits.globalcase class MyBoard(id: Option[Int],name: String)case class MyList(id: Option[
我有一个宠物
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 [[ErrorCreatingList,List [MyList]]]但我不知道怎么做,因为listsWithId的类型为List [Future [scala.Either [ErrorCreatingList,MyList]]],这使得感. 有办法吗?一位朋友告诉我“这就是Cats的用途”,但这是唯一的选择,我的意思是,我不能只使用Scala核心库中的内容吗? 谢谢. 解决方法
在列表[Future [???]]上使用Future.sequence来创建Future [List [???]]
val listOfFuture: List[Future[???]] = ??? val futureList: Future[List[???]] = Future.sequence(listOfFuture) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |