gpt4 book ai didi

Scala Option[Future[T]] 到 Future[Option[T]]

转载 作者:行者123 更新时间:2023-12-03 11:35:51 32 4
gpt4 key购买 nike

如何转换 Option[Future[T]]Future[Option[T]]在斯卡拉?

我想在以下方面使用它:

val customerAddresses = for {
a <- addressDAO.insert(ca.address) // Future[Address]
ia <- ca.invoiceAddress.map(addressDAO.insert) // Option[Future[Address]]
} yield (a, ia) // Invalid value have to be two futures

这里签名插入方法
def insert(address: Address): Future[Address]
ca是客户数据
case class CustomerData(address: Address, invoiceAddress: Option[Address])

最佳答案

import scala.concurrent.Future
import scala.concurrent.ExecutionContext

def f[A](x: Option[Future[A]])(implicit ec: ExecutionContext): Future[Option[A]] =
x match {
case Some(f) => f.map(Some(_))
case None => Future.successful(None)
}

例子:
scala> f[Int](Some(Future.successful(42)))
res3: scala.concurrent.Future[Option[Int]] = Success(Some(42))

scala> f[Int](None)
res4: scala.concurrent.Future[Option[Int]] = scala.concurrent.impl.Promise$KeptPromise@c88a337

关于Scala Option[Future[T]] 到 Future[Option[T]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38226203/

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