[Play 2.x Scala] Good patterns for less messy mixing of monads and conditionals

131 views
Skip to first unread message

Johan Andren

unread,
Sep 27, 2013, 7:26:51 AM9/27/13
to play-fr...@googlegroups.com
With async code I often find myself doing variations on this theme:

def doSometh(id: Long) = Action(parse.json) { request => Async {
  val someData: Option[String] = (request.body \\ "someField").asOpt[String]

  someData.map { data => 
    // returns Future[Option[Model]]
    SomeDao.find(id).flatMap { maybeModel: Option[Model] => 
      maybeModel.map { model => 
        SomeDao.doSomething(model, data).map(Ok("Youre alright!"))
      } getOrElse {
        Future.successful(NotFound(s"No model with id $id exists"))
      }
    }
  } getOrElse {
    BadRequest("Expected 'someField' in the posted json")
  }
}}

Anyone has some good ideas to make this kind of code more concise and less different-levels-of-nestedness:y? 

We built a FutureMaybe monad class so that we can do for comprehensions when we have multiple nested Future[Option[_]] and can react with one error message for Future[None] at any level, but when we want to return different errors at different stages like the above it does not really help.

Raul Raja

unread,
Sep 27, 2013, 8:44:57 AM9/27/13
to play-fr...@googlegroups.com, Johan Andren
Hi Johan,

I face the same issue. For comprehensions are great but as you pointed out they don't combine well when mixing Futures with other monads.

With the increasing number of Future based async api's this issue is even more annoying.

We use Reactive Mongo extensively with Play and observe the same pattern all over the place.

Here is a link to a similar discussion on the scala-user group in case it is of any help

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framewor...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
Reply all
Reply to author
Forward
0 new messages