I've been looking at a lot of Scala monad transformer examples and haven't been able to figure out how to do what I think is probably something straightforward. I want to write a for
comprehension that looks up something in a database (MongoDB), which returns an Option
, then if that Option
is a Some
, looks at its contents and gets another Option
, and so on. At each step, if I get a None
, I want to abort the whole thing and produce an error message like "X not found"
. The for
comprehension should yield an Either
(or something similar), in which a Left
contains the error message and a Right
contains the successful result of the whole operation (perhaps just a string, or perhaps an object constructed using several of the values obtained along the way).
So far I've just been using the Option
monad by itself, as in this trivial example:
val docContentOpt = for {
doc <- mongoCollection.findOne(MongoDBObject("_id" -> id))
content <- doc.getAs[String]("content")
} yield content
However, I'm stuck trying to integrate something like Either
into this. What I'm looking for is a working code snippet, not just a suggestion to try \/
in Scalaz. I've tried to make sense of Scalaz, but it has very little documentation, and what little there is seems to be written for people who know all about lambda calculus, which I don't.