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

(x:Int,y:Int) => x+y

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

var sum = (x:Int,y:Int) => x+y

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

println(sum(5,7))

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.

Traits in Scala- Deep Dive

Traits are units of code reuse in Scala. Traits encapsulates methods and field definitions. Their role is similar to that of interfaces in Java- A workaround for Multiple Inheritance. But unlike Interfaces they can have method and field definitions. More features will be explained in the article.

Defining Traits:

A trait definition looks like a class definition but uses the keyword “trait.

trait Bounceable{

     def bounce():String="Bounce Method in Trait"

}

The above declared trait has a concrete method. The ability to declare concrete methods in an trait gives default implementation option. In interfaces one has to write/copy-paste the default declaration in each class which implements the interface or declare a class that implements that interface and let other classes extend the concrete class. The first method has code repition and the second method has the restriction that a class can extend only one class. So this feature of “trait” stands out best.

As in Java a class implements interface, in Scala classes traits are mixed into a class. This is done using either extends or “with” keywords.

class Ball(s: Int) extends Bouncable{

      var size:Int

      override def toString():String= Integer.toString(size)

}

In the above example we are using extends to mix in the trait- Here Ball is implicitly inherits trait’s superclass which is “AnyRef”. Lets try to use the class Ball to test the mixed in trait.

object Test{

           def main(args:Array[String])={

                    var ball = new Ball(33)

                    var ball2:Bounceable= new Ball(400)

                    println(ball.bounce()) //This prints "Bounce Method in Trait"

                    println(ball) //This prints "33"

                    println(ball2.bounce())

                    println(ball2)

         }

}

Note: Output written as comment.

Regarding the ball2 instance being declared as type “Bounceable”. Its a valid declaration cause supertype references can refer to the instances of its subtypes. But they cannot access the methods/fields declared by the subtypes (different with the overriding case).

Continue reading Traits in Scala- Deep Dive

How’s Scala different from Java?

  • Scala is statically type like Java but with Type Inferencing support. Which means that the scala compiler analyzes the code deeply to determine what type a particular value is.
  • In Scala its not required to use semicolons to terminate a statement if the termination is obvious by line ending. If there are more than one statements on the single line then they have to be separated by using semicolon.
  • Scala doesnot require the file containing a class definition to mirror the name of the class.
  • In Scala there’s no use of static all together. This is replaced by use of singleton object. Singleton objects are declared by using the keyword “object” and not “class”.
  • In Scala, arrays are instances of Array class and uses square brackets ([]) instead of angle brackets (<>) to indicate parameterized types.
  • In Scala the variable declaration is: “name: type”
  • Scala uses keyword “Unit” to represent functions which return “non-value” value.
  • In Scala the syntax for method declaration is different. It uses the “=” before the method body preceeded by the identifier/name of the method along with the parameter list and return type. Functions are treated like variables and constants.
  • Scala supports the use of closures, Annonymous functions- Which makes longer code simpler and shorter.

These were few things i have noted. There are lot more differences. If u know any please add it as a comment. Will upadate my post accordingly.

Control Structures in Scala- A brief overview

If Statements:

Lets consider a first entry example of If statments, without using much of Scala’s features.


if(5+6==10){

println("You are wrong in calculations")

}else{

println("Keep it up")

}

This is a pretty simple and straight forward examples. Now lets add some Scala flavor in the If-Statement. In Scala If-Statements are expressions, which means that the value from If-Statements can be assigned to some variable. Lets consider another example- Finding greatest of two numbers.

Note: I am using the scala interpreter.

scala>var num1=54
num1:Int=54
scala>var num2=76
num2:Int=76

I have created 2 variables. We will have to write a If-Statement for finding out the greatest value and assign it to another variable.

scala>var big=if(num1>num2){ num1}else{num2}
big:Int=76
scala>println(big)

One can see how the result from a if-expression is assigned to a variable. This feature of If construct has removed the need of a Select case construct. Also note that the Type Inference coming into play there- I haven’t mentioned tat big is a Int but it has inferred based on the If-Statement that it will hold an Int. If we had missed the else part then it would have inferred the type to be Unit (void in Java).

For Loops-

In the Scala world they are also referred to as the “For Comprehension” or “For Expression”. Let’s consider a example list.

scala> var cities=List(“Bangalore,India”, “Delhi, India”, “Chennai, India”,”Tokyo, Japan”, “New York, USA”, “London, UK”, “Paris, France”)

The above code will create a List of Cities along with their countries.  Now lets use a for loop to “comprehend” the list.


scala> for(city <- cities)println(city)

Straight forward and simple. The left arrow operator (<-) is called as “generator” as it is used to generate elements from the list. Now lets print the cities in India with the help of the Scala’s features


scala>for(city <- cities if city.contains("India"))println(city)

Bangalore,India

Delhi, India

Chennai, India

The above technique is called “Filtering“. One can add multiple filers (if condition) and the filers have to be seperated by using “;”.  Now suppose we want to store the Indian cities in a separate list, what do we do? Scala does have a solution to that as well. Lets look at the code:


scala> var indianCities=for(city <- cities if city.contains("India"))yield city

scala>for(city <-indianCities)println(city)

Bangalore,India

Delhi, India

Chennai, India

The type of the yielded list has not been mentioned. Scala infers the type from the Type of the Collection being used to yeild a new List.

While and Do-While Loops:

While loops, as in other languages, execute the code in the block until the condition is true. Do-While is similar to While the only difference being that the loop is executed at least once and checks to see if the condition is true or not.

Example to find sum of first 10 natural numbers


scala> var i=1

scala>var sum=0

scala>while(i<=10){ sum=sum+i;i=i+1}

scala>println(sum)

An example to show do while loop:


scala>sum=0;i=0;

scala>do{ sum +=i;i+=1}while(sum<100)

scala>println(i)

That was a brief overview of If, For, While and Do-While constructs.