Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best handle Future.filter predicate is not satisfied type errors

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?

like image 911
Blankman Avatar asked Jan 03 '16 02:01

Blankman


2 Answers

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)

like image 113
Alvaro Carrasco Avatar answered Jan 06 '23 06:01

Alvaro Carrasco


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)
                          }
like image 23
Jean Logeart Avatar answered Jan 06 '23 07:01

Jean Logeart