patternMinor
Returning preferences
Viewed 0 times
preferencesreturningstackoverflow
Problem
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:
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)
}
}Solution
The only alternative is using a
Unfortunately you cannot use the
for comprehension:for {
hasAccess <- canAccessPreferences(id)
result <- if (hasAccess)
Future.successful(Forbidden)
else
doGetPreferences(id)
} yield resultUnfortunately 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.Code Snippets
for {
hasAccess <- canAccessPreferences(id)
result <- if (hasAccess)
Future.successful(Forbidden)
else
doGetPreferences(id)
} yield resultContext
StackExchange Code Review Q#83391, answer score: 2
Revisions (0)
No revisions yet.