假设我们有:
val listOfYetToBeMaybePeople = List[Future[Option[Person]]]
有没有一种非阻塞的方式来获得 Future[Boolean]
的 true
当且仅当所有元素都有 Some(Person)
或 false
如果至少有一个是 None
?
最佳答案
试试这个:
val listOfYetToBeMaybePeople: List[Future[Option[Person]]] =
val allExist: Future[Boolean] =
Future.sequence(listOfYetToBeMaybePeople).map(_.forall(_.nonEmpty))
解释:
sequence
将Future
的List
转换为列表的 futureforall
检查列表中所有元素的谓词nonEmpty
检查一个Option
是否实际上是一个Some
。
如果所有人都存在,则返回带有 true
的 future 。
关于scala - 如何检查 Future[Option] 列表中是否存在 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48891122/