Option Monad in Scala
We will see option Monad in Scala as follows:
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala>val a:Option[Int] = Some(1)
a: Option[Int] = Some(1)
scala>a.get
res0: Int = 1
scala>val b:Option[Int] = None b: Option[Int] = None scala>b.get
java.util.NoSuchElementException: None.get at scala.None$.get(Option.scala:347) at scala.None$.get(Option.scala:345)
... 32 elided scala>b.getOrElse(0) res2: Int = 0 scala>a == b res3: Boolean = false scala>
In Haskell, this also known as the Maybe monad. Option means optional value, because we are not 100% sure if the value will be present. In order to express a value, we use the Some type, and in order to express the lack of value, we use none. Option Monads are great, they make your code more explicit, because a method might receive or return an option, which means you are explicitly saying this could be null. However, this technique is not only more expressive but also safer, since you won't get a null pointer, because you have a container around the value. Although, if you call the method get in Option and it is none, you will get a NoSuchelementException. In order to fix this, you can use the method getOrElse, and you can supply a fallback value which will be used in the case of none. Alright, but you might be wondering where the flatMap method is. Don't worry, Scala implements this method for us into the Option abstraction, so you can use it with no issues.
scala>val c = Some("one") c: Some[String] = Some(one)
scala>c.flatMap( s => Some(s.toUpperCase) ) res6: Option[String] = Some(ONE)
The Scala REPL can perform autocomplete for you. If you type C + Tab, you will see all the available methods for the Some class. The map function is available for you to use, and as I said before, there is no unit function in Scala whatsoever. However, it is not wrong if you add in your APIs.