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.
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
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 {
...
}
(as Jean Logeart's answer, but within a for-comprehension)
You probably want to use a simple flatMap
in which you can specify an else
case:
val orders = accountServer.get(...)
.flatMap { account =>
if(account.isConfirmed) orderService.get(account, ...)
else Future.successful(Seq.empty)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With