gpt4 book ai didi

scala - future [选项[T]] : Keep future if Option is defined otherwise fallback to another future

转载 作者:行者123 更新时间:2023-12-02 09:06:20 26 4
gpt4 key购买 nike

我有这个 val cacheElement:Future[Option[T]] 并且期望的结果是如果 OptionSome 则保留这个 future code> 或如果 future 是 None,则基于另一个服务创建另一个 Future[Option[T]]。使用模式匹配,这看起来像这样:

val cacheElement:Future[Option[T]] = cache.get[T](cacheKey)

for {
opt <- cacheElement flatMap {
case Some(cached) => Future { Some(cached) }
case None => createFallback(args)
}
} yield { opt match {
case Some(_) => //do something
case None => // Do something else
}
}


def createFallback[T](args:T):Future[Option[T]] = ???-

我怎样才能以更优雅和简洁的方式做到这一点? Future { Some(cached) } 的重复对我来说看起来非常冗长

最佳答案

import scala.concurrent.Future
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

type T = String

val cacheElement: Future[Option[T]] = Future.successful(Some("asd"))
val failElement: Future[Option[T]] = Future.successful(None)

def createFallback: Future[T] = Future.successful("fallback")

val s = cacheElement.flatMap(_.fold(createFallback)(Future.successful))
val f = failElement.flatMap(_.fold(createFallback)(Future.successful))

Await.result(s, 1.second)
//res0: T = asd
Await.result(f, 1.second)
//res1: T = fallback

关于scala - future [选项[T]] : Keep future if Option is defined otherwise fallback to another future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990483/

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