gpt4 book ai didi

scala - 处理 future 和选择的干净方式

转载 作者:行者123 更新时间:2023-12-04 17:54:08 27 4
gpt4 key购买 nike

我的代码块目前看起来像这样,看起来很难看:

for {
maybeUser <- getUser(1)
} yield {
if (maybeUser.isDefined) {
someFunction1(maybeUser.get)
} else None
}

getUser 的样子:

def getUser(id: Int): Future[Option[user]]

最佳答案

你应该可以这样:

for {
maybeUser <- getUser(1)
} yield {
maybeUser.map(someFunction1)
}

这将产生一个 Option[T](其中 TsomeFunction1 的返回类型),这应该是您想要的。

对于 Option 模式的精彩总结,我强烈推荐这篇文章:Your Options Don't Match

关于scala - 处理 future 和选择的干净方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41411553/

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