Friday, September 23, 2016

When to use 'Nothing'...

scala> //One of the usage of Nothing is with

scala> //abnormal program termination #253

scala>

scala> ///////////////////////////////////

scala> //  An Example WITHOUT Nothing

scala> ///////////////////////////////////

scala> def error(msg:String): Unit = {
     |   println("Message.. is -> " + msg)
     |   throw new RuntimeException(msg)
     | }
error: (msg: String)Unit

scala>

scala> def isValidNo(no: Int):Boolean = {
     |   if(no == 0) {
     |     error("Invalid no")
     |   }else {
     |     true
     |   }
     | }
<console>:45: error: type mismatch;
 found   : Unit
 required: Boolean
           error("Invalid no")
                ^

scala>

scala> ///////////////////////////////////

scala> //  An Example WITH Nothing

scala> ///////////////////////////////////

scala> def error(msg:String): Nothing = {
     |   println("Message.. is -> " + msg)
     |   throw new RuntimeException(msg)
     | }
error: (msg: String)Nothing

scala>

scala> def isValidNo(no: Int):Boolean = {
     |   if(no == 0) {
     |     error("Invalid no")
     |   }else {
     |     true
     |   }
     | }
isValidNo: (no: Int)Boolean