3
\$\begingroup\$

I have a function that returns some preferences, but first I have to do some checks to see whether the user is authorised to read them. I'm still not happy with the result (the match is a bit ugly).

Note: Result is a framework class, it just means some kind of response.

// implementations are not relevant.
def canAccessPreferences(id: Long): Future[Boolean] = ???
def doGetPreferences(id: Long): Future[Result] = ???

def getPreferences(id: Long) = Future[Result] {

  canAccessPreferences(id).flatMap {
     case false =>
       Future.successful(Forbidden)
     case true =>
       doGetPreferences(id)
  }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Curious that you are going to some effort of abstraction with futures and framework classes but have hard coded your id everywhere as Long. Such an important type should have a type alias. \$\endgroup\$
    – itsbruce
    Mar 6, 2015 at 15:23

1 Answer 1

2
\$\begingroup\$

The only alternative is using a for comprehension:

for {
  hasAccess <- canAccessPreferences(id)
  result <- if (hasAccess)
    Future.successful(Forbidden)
  else
    doGetPreferences(id)

} yield result

Unfortunately you cannot use the if guard of the for because then you would get an exception if hasAccess is false. And since you're composing Future monads there's no way around the Future.successful either.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.