|
|
|
|
|
by runT1ME
4438 days ago
|
|
> for-comprehensions often don't cut it when you're dealing with a Future[Option[User]] and need to pull in their assigned roles from a Future[Seq[Role]]. If you aren't familiar with Monad Transformers, yes, it can be tricky. However it's trivial using an Option monad transformer (OptionT[Future,A]]) to have the same semantics. for {
user <- OptionT(db.get(userId)
mappedRoles = user.roleIds.map(db.get(_))
roles <- mappedRoles.sequence.liftM //goes to OptionT[Future,A]]
} yield user.copy(roles = roles.flatten)
Look at http://github.com/scalaz for already built Monad Transformers (Either/State/Option/Writer) that will work with the standard lib Future along with tons of other goodies. I actually actively dislike the async stuff as it gives you another way of doing the same thing, at a less powerful abstraction. |
|
I like the async/await stuff. Especially after attending the ScalaDays presentation on it. The idea that it produces a state machine in the background feels like it's very easy to reason about.
I actually (personally) find for-comprehensions the least useful feature of Scala probably. They rarely produce the most readable code IME with just a couple transformations in play, and it's not often I find myself dealing with compatible types in the more complex cases.
So I guess I consider async/await the readable/prettier alternative to direct mapping that for-comprehensions mostly fail to deliver on. for-comprehensions are probably Scala's second biggest wart IMO (not harmful, more just mostly useless). YMMV. Sort of like `__DATA__` or `=BEGIN/=END` in Ruby.