Scala – Option pattern and monadic for expressions

 

package nag.arvind.gudiseva.app
/**
 * Created by Nag Arvind Gudiseva on 12-Apr-2016.
 * We need Burger and need Chicken and Tikka object.  Also the calls for retrieving Chicken and Tikka may or may not return a value.
 * For example: Each method 1. maybeChicken 2. maybeTikka and 3. maybeBurger have capability to either return a proper or empty value.
 * Instead of null kind of check for each method: we can use Option pattern and monadic for expressions to write a clean code that accounts for the checks.
 *
 */
object CleanCodeApp extends App with ChickenTikkaBurgerService {

  val BurgerOption = for {
    chicken <- maybeChicken
    tikka <- maybeTikka(chicken)
    burger <- maybeBurger(tikka)
  } yield burger

  BurgerOption match {
    case Some(burger) => println("We have a Burger")
    case None => println("We do not have a Burger")
  }
}

trait ChickenTikkaBurgerService {
  def maybeChicken : Option[Chicken] = Some (new Chicken())
  def maybeTikka(chicken: Chicken) : Option[Tikka] = Some (new Tikka())
  def maybeBurger(tikka: Tikka) : Option[Burger] = Some (new Burger())
}

class Chicken
class Burger
class Tikka
Result: We have a Burger

 

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