我在一个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]]]
,这是有道理的。有没有办法做到这一点? 一个朋友告诉我“这就是Cats的用途”,但它是唯一的选择吗? 我的意思是,我不能只使用Scala核心库来完成吗?
谢谢。