Option vs null

What is Option[T]?

Official definition:
It represent optional values. Instances of option are either an instance of Some or the object None.

Simple definition:
It's a container.

How do we solve the null problem?

Java approach

Scala approach

val person:Person = getPersonById(id)
if (person != null) {
              getEmail(person);
}
val maybePerson: Option[Person] = getPersonById(id)
maybePerson match {
          case Some(person) => getEmail(person)
          case None => // do nothing or something else}

So why option is better?

Honest function signatures

Dishonest:

Honest:

def getPersonById(id: Int):Person 
def getPersonById(id: Int):Option[Person]

Option is a monad !

Imagine Option as a collection of 1 or o elements.

Chaining multiple function calls:

val x: Option[Int] = getPerson()
x.foreach(person =>getEmail(person))
getPerson().map(getEmail(_))
                    .map(getHost(_))
                    .map(writeToDb(_))

Try vs try/catch

What is Try[T]?

Official definition:
The Try type represents a computation that may either result in an exception, or return a successfully computed value. 


Simple definition:
It's a container.

Java approach

Scala approach

How do we manage errors?

URL parseURL(String url) throws MalformedURLException {
     try { new URL(url); }
     catch(MalformedURLException e){ 
              throw e;
        }
}
def parseURL(url: String): Try[URL] = Try(new URL(url))

Working with Try's

Or

Chaining multiple Try's

parseURL(url) match {  
          case Success(url) => url
          case Failure(ex) => Log.error(ex)
} 
parseURL(url) .map(url => openConnection(url))
   for {
          url <- parseURL(url)
          connection <- Try(url.openConnection())
          stream <- Try(connection.getInputStream)}  
    yield stream

Optional vs null

By Corneliu Caraman

Optional vs null

  • 178