如何最好地处理Future.filter谓词不满足类型错误 [英] How to best handle Future.filter predicate is not satisfied type errors
问题描述
我喜欢scala如何保证类型安全,但是我一直遇到的一个运行时错误是
I love how scala is type safe, but one runtime error I keep running into is
Future.filter predicate is not satisfied
我可以看到我为什么会收到此错误,只是在寻找有关如何最好地解决此错误并优雅地处理该错误的建议,或者我做错了吗?
I can see why I am getting this error, just looking for advice on how to best work around this error and handle it gracefully or maybe I am doing this wrong?
val r: Future[play.api.mvc.Result] = for {
account <- accountServer.get(...)
if account.isConfirmed
orders <- orderService.get(account, ...)
} yield {
...
}
如果未确认帐户,我会收到上述错误.
If the account is not confirmed, I will get the above error.
我会认为,由于过滤器可能会发生故障,因此scala会将yield return值设为Option.不?
I would have thought that since there is a potential for the filter to fail, that scala would then make the yield return value an Option. No?
推荐答案
filter
对于Future
没有意义,因为类型系统不知道对于else
情况返回什么,所以不安全地依靠它(使用if-guard).但是,您可以凭一己之力做到这一点,以实现相同的目的:
filter
doesn't make sense for Future
since the type system wouldn't know what to return for the else
case, so it is unsafe to rely on it (by using an if-guard). But you can do this within a for-comprehension to achieve the same thing:
val r: Future[play.api.mvc.Result] = for {
account <- accountServer.get(...)
orders <- if (account.isConfirmed) orderService.get(account, ...)
else Future.successful(Seq.empty)
} yield {
...
}
(这是让·洛格(Jean Logeart)的回答,但要理解)
(as Jean Logeart's answer, but within a for-comprehension)
这篇关于如何最好地处理Future.filter谓词不满足类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!