Scala and Monad Tutorial

Scala Monads: Declutter Your Code With Monadic Design

I had been staying out of the keyword “monad” as it’s often described as difficult. But, this tutorial video nicely explains it with concise and clean examples.

It’s interesting to explain monad as “design pattern” in the functional programming world. Also, the example compares normal Java-way of handling null and exceptions with monadic-way ones in Scala.

[Java]

if (foo != null) {
  Bar bar = foo.getBar();
  if (bar != null) {
    Baz baz = bar.getBaz();
    if (baz != null)
      return baz.computer();
    else
      return null;
  }
  else
    return null;
}
else
  return null;

[Scala]

for {
  foo <- maybeFoo
  bar <- foo.bar
  baz <- bar.baz
} yield baz.compute

Pretty much concise. When I was learning Scala at coursera course, I could understand the basics (for statements, Option with Some/None and map/flatmap concepts), but I wasn’t thinking about its underlying concepts like monad. It would be worthwhile to dig-deep a little more.

Advertisements

Posted on June 26, 2014, in Conference, Java, Software Design. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: