Does anyone have a full worked example of a Scala monad that tackles a real-world problem and has comparisons to the same code written in Java?
-
While not a scala example, this is a rather in-depth study of the Maybe monad in Java (with some Haskell notes to see how more capable languages can deal with this): http://logicaltypes.blogspot.com/2011/09/monads-in-java.html – Jason Sperske Feb 26 '13 at 17:44
-
3The concept of Monad is not as strange as it seems (or its name makes it seem). For better or worse, this terminology from Category Theory is immensely practical, but the zeitgeist of programming today is to strongly de-emphasize (even derogate) theory. To my mind, this is a disgrace and disqualifies software from the realm of "engineering" – Randall Schulz Feb 26 '13 at 21:05
3 Answers
All collections are monads (that's a general statement, not a Scala-specific one), or "have monads" depending on how strict you want to be about it. Scala also has Option
as a monad, and the right and left projections of Either
as well. You can see their monadic aspects at work whenever you see a for-comprehension with them.
A more subtle example of monads in Scala is the parser combinators. It is more subtle because the operators hide the monadic operations behind synonyms that look better in a grammar.

- 295,120
- 86
- 501
- 681
def optionAdd(x:Option[Int], y:Option[Int]):Option[Int] =
for(xx <- x; yy <- y) yield xx+yy
I don't dare wasting time with the java version, specially because someone greatly smarter than me already did http://functionaljava.org/examples/1.5/#Option.bind. The example in link is doing basically what optionAdd
does in a infinitely less concise way.

- 12,763
- 1
- 38
- 49
see http://jazzy.id.au/default/2012/11/02/scaling_scala_vs_java.html
Eg async call using monads to four clients:
for {
user <- getUserById(id)
orders <- getOrdersForUser(user.email)
products <- getProductsForOrders(orders)
stock <- getStockForProducts(products)
} yield stock
Futues are monadic and for comprehensions can be used to compose asynchronous code
In java well... start waiting Monads with Java 8