A brief introduction to using Option and Either classes

Previously I had written about Companion classes in Scala and there in I had mentioned one of its uses i.e defining the apply method to support object literals. In this post I am continuing from where I had previously left and pick two such Companion classes in Scala API called the Option class and the Either class and their associated case classes.

In this post I would like to cover:

What are case classes?

From the Official Scala Doc:

Scala supports the notion of case classes. Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.

Examples of the case classes include scala.Some, scala.util.Left, scala.util.Right. And the application of case classes can be read in the below topics.

What is Option class?

From the Scala API, Option class:

Represents optional values. Instances of Option are either an instance of scala.Some or the object None.

Prior to Java 8, there is no support for creating objects which either hold some value or dont hold any value. This support has been provided by external APIs like Guava and others. In Java 8 there is a new class added called Optional ( I would write about this sometime in future).

There are 2 variants of Option namely Some and None. The former represents presence of a value and stores the value within it and the latter represents the absence of value. Lets have a look at an example:

//Uses of Option class
object OptionDemo {
  def main(args: Array[String]) {   
    val result1 = loadData(true)
    val result2 = loadData(false)
    println(result1.getClass())//Prints class scala.Some
    println(result2.getClass())//Prints class scala.None$

    //getOrElse- either returns the value present or 
    //returns the value after evaluating the parameter.
    println(result1.getOrElse("Error!"))
    println(result2.getOrElse("Error!"))
    
  }

  def loadData(condition: Boolean): Option[String] =
    if (condition) {
      Some("Data found!")
    } else {
      None
    }

}

In the above simple example an instance of Some or singleton None is returned by the loadData based on some condition and then make use of the return values to print out the their types as well as their contents using the getOrElse method. Lets see another way to make use of the return values from the loadData method. In the below example we make use of the advanced pattern matching mechanism to extract the contents of the object. This is possible because the classes Some and None are case classes.

object OptionDemo {
  def main(args: Array[String]) {   
    val result1 = loadData(true)
    val result2 = loadData(false)
    
    //Prints: found details:Data for employee 1234
    matcher(result1)
    //Prints: No data found
    matcher(result2)
  }
  
  //Using pattern matching to decompose the parameter.
  def matcher(result: Option[String]){
    result match{
      case Some(msg) => println("found details:" + msg)
      case None      => println("No data found")
    }
  }

  def loadData(condition: Boolean): Option[String] =
    if (condition) {
      Some("Data for employee 1234")
    } else {
      None
    }

}

What is Either class?

From the Scala API, Either class:

Represents a value of one of two possible types (a disjoint union.) Instances of Either are either an instance of scala.util.Left or scala.util.Right.

And just after the it states the use of Either class:

A common use of Either is as an alternative to scala.Option for dealing with possible missing values. In this usage, scala.None is replaced with a scala.util.Left which can contain useful information. scala.util.Right takes the place of scala.Some. Convention dictates that Left is used for failure and Right is used for success.

In the below example we make use of Left class to populate the data is some operation is successful and make use of Right class to populate the exception message in case of failure. The success condition is when the passed number is even and the failure condition is when the passed number is odd.

object EitherDemo {
  def main(args: Array[String]) {
    val div1 = even(12)
    val div2 = even(11)
    matcher(div1)//Prints 12.0
    matcher(div2)//Prints "The number 11.0 is not even"
    
  }
  
  def matcher(matchElement:Either[String, Double]){
    matchElement match {
      case Left(msg) => println(msg)
      case Right(rem) => println(rem)
    }
  }

  def even(number:Double): Either[String, Double] =
    if (number % 2 == 0) {
      Right(number)
    } else {
      Left("The number "+ number +" is not even");
    }

}

In the above example Left and Right case classes have been used in pattern matching in the same way the classes Some and None were used in the first example.

This was in very brief about Option and Either classes in Scala and how case classes can be used for pattern matching.

Brief overview of An “object” in Scala

In Java world we are all familiar with the term object and interchangeably use it with the term instance. Both these terms represent initialization of a class with the required parameters. But the same cannot be applied in Scala, because in Scala “object” is a keyword and represents a totally different but somewhat related concept. Its totally different because “object” keyword represents a single instance of that with which it is used. And similar because it still represents some instance.

I have divided the post into different sections namely:

  1. Simple example of object
  2. An example of inbuilt object in Scala library
  3. Companion classes and Companion objects
  4. Companion object with apply method

Continue reading Brief overview of An “object” in Scala

Book Review: Scala for the Impatient

  • The book covers almost all of the concepts in Scala in a very concise format.
  • More emphasis on learning by doing.
  • Lot of exercise problems at the end of each chapter. It is highly recommended to try them out.
  • The concepts have been divided into varying difficultly levels and the chapters have been arranged so as to facilitate good understanding.
  • The initial few chapters help Java programs to get onto programming in Scala by not scaring with Functional style of programming.

Some of the not so good things:

  • You dont get to see lot of idomatic scala code. Unlike Core Java where the examples gave the reader an idea of how to organise code. It is acceptable considering the size of the book.
  • The questions dont have solutions so its difficult to evaluate if your code follows best practices.

This would not be the last book you would read, I am sure once you finish this book you would be in a better position to read other Scala books and try to grasp the advanced scala concepts and also learn to write idomatic scala code.

The ideal approach to read this book is to practice the exercises and also keep the Scala API documentation handy.

Being a newbie with lot of failed efforts to learn Scala, I found this book to be easy to pick scala concepts and also familiarize with the code.

This review was originally posted at: Javaranch Book Review and I received a copy of the book for the reveiw.

Partially applied functions in Scala

Before going into Partially applied Functions, let me introduces 2 terms-
Function Literal- This exists in the source code- Something similar to Class definition. So we have

[scala gutter=”false”]
(x:Int,y:Int) => x+y
[/scala]

Function value- When this function literal is assigned to a reference they become function values. The are similar to the Objects created from the class. These are created at runtime

[scala gutter=”false”]
var sum = (x:Int,y:Int) => x+y
[/scala]

So in the above case we can use sum to invoke the method.

[scala gutter=”false”]
println(sum(5,7))
[/scala]

Continue reading Partially applied functions in Scala

Brief insight into Constructors in Scala

In the previous post here, I had introduced few concepts related to constructors in Scala. In this post I would go a bit deeper into the constructors and how we can provide different constructors. Summarizing about the introduction in the previous post here
Continue reading Brief insight into Constructors in Scala

Object Oriented Programming in Scala- 1

Scala uses both Object oriented and functional programming concepts. For folks coming from the Java, we would always explore how to do OOP in Scala. Here I thought of writing few posts related to OOP in Scala (may be a Series of posts ;)). In this post lets talk about-

  • Classes
  • Objects
  • Constructors
  • Overloaded Constructors

Continue reading Object Oriented Programming in Scala- 1

Null, null, Nil, Nothing, None, and Unit in Scala

Null– Its a Trait.
null– Its an instance of Null- Similar to Java null.

Nil– Represents an emptry List of anything of zero length. Its not that it refers to nothing but it refers to List which has no contents.

Nothing is a Trait. Its a subtype of everything. But not superclass of anything. There are no instances of Nothing.

None– Used to represent a sensible return value. Just to avoid null pointer exception. Option has exactly 2 subclasses- Some and None. None signifies no result from the method.

Unit– Type of method that doesn’t return a value of anys sort.

Note: Any is supertype of AnyRef and AnyVal. AnyRef is the supertype of all the reference classes (like String, List, Iterable) in scala. AnyVal is the supertype of all the value classes (like Int, Float, Double, Byte, Short..). Null is a subtype of all the reference classes. null is its only instance. Nothing is subtype of every other type i.e of reference and value classes.

Think- AnyRef == Object in Java.

The above is a breif summary of a wonderful post by Matt Malone where he has explained all these concepts in depth with examples. Read the blog post here.