Scala Either Monad

Either is one of the most useful monads in Scala. Its similar like Scala Option.
In this post, we are going to see how we can use this with an example.

Scala.Either

  • Its an abstract class extends Product.
  • Its an alternative to Option Monad.
  • An instance of Either is either an instance of scala.util.Left or scala.util.Right.
  • Left is used for failure and Right is used for success.
  • Mainly used in error handling.
  • The returned value is either an error or valid value.

Assume that we have a function and want to do some operation before doing that we want to do some validation and throw an error if the validation fails otherwise perform the operation and return the value.

Lets refer the below example to know how to do that with “Either” Monad.

ScalaEitherExample

The output is given below,

ScalaEitherExampleOutput

In the above example, we have a function “divide” which takes two values and perform divide operation and then return a result.

If the divisor is zero, then it will throw an error. So we first validate it and if the divisor is zero, then we will wrap the error in a case class “CalculationError” and return an instance of Left which represents an error.

If there is no error, then we will perform the divide operation and return the result as an instance of “Right” which represents success scenario

Scala String Interpolation

String interpolation is a feature of Scala and it enables us to embed variable references directly in processed string literals.

We have three kinds of Scala String interpolators. Let’s see them one by one.

s String interpolator
f String interpolator
raw String interpolator

s String interpolator:

When we prepend ‘s’ to any string, we can directly use variable in it with the use of $ character. But that variable should be in scope.


  val name = "John"
  println(s"My Name is $name")  // My Name is John

f string  interpolator
When we prepend ‘f’ to a processed string literal which allows  the creation of formatted strings, Its similar to “printf” in Java.


val height = 1.9d
val name = "John"
println(f"$name%s is $height%.2f meters tall")  // John is 1.90 meters tall

raw interpolator
It’s similar to ‘s’ interpolator except that it performs no escaping of literals within the string.

Refer the below example,


val name="John"
println(s"My name is \n$name")  //My name is
                                //John  

Here the s interpolator, replaced the character \n with a return character.  The “raw” interpolator will not do that.


val name="John"
println(raw"My name is \n$name") //My name is \n John

Scala App Trait

Scala contains a trait called “App” and its used to turn objects into executable programs.

We do not need to explicitly define “main” method in a Scala object, instead the whole class body becomes the main method.

Refer the below example,

ScalaMainApp

In the above code, we define an object “ScalaMain” and in the body of that object, we define a function “add” for adding two numbers. The whole code section becomes the main method.

Scala Case Class

Scala class classes are like regular classes but with a few differences.  Those are given below.

Differences:

  • When we create a case class, it also creates a companion object implicitly with apply and unapply methods.
  • By default, Case classes are serializable.
  • Case class instances can be created without using the new keyword.  By default, the apply method of case class companion object will be called and it creates an instance of case classes.
  • Suitable for modeling immutable data.
  • Case classes automatically define the toString, equals and hashCode methods.
  • Case class constructor parameters are public val’s. So we can’t modify the values once it’s assigned. Because those parameters are immutable or constant.
  • Case classes automatically define the getter methods for constructor arguments.
  • It can be used in Pattern Matching operation.
  • It contains an implicit ‘copy’ which is used for creating a copy of a case class instance. We can also optionally change the constructor arguments.
  • Scala case classes can’t be extended by other case class.

CaseClass.JPG

Scala val, var and def

In this post, we are going to see the difference between var, val and def keywords of Scala.

Var –  If you want to create a mutable variable in Scala, then you have to use var keyword. For example, you want to create a variable and the value of that variable will be changed, then you need to use var keyword to define a mutable variable.

Val –  If you want  to create an immutable variable, then you have to use val keyword. Its like creating a constant value so once the value is assigned to a variable, then its never going to change. Even if you do, then you would get a compilation error.

def – To define a function, then you have to use this keyword.

Refer the below example, to know how to use these keywords.

val keyword usage:

In the below example, we use the ‘def’ keyword to define a function. We create a variable with ‘val’ keyword and then try to modify the value once its assigned. So when you do that, then you would get a compilation error.

ScalaExampleWithVal

var keyword usage:

ScalaExampleWithVar

Scala Extractor Objects

An Extractor object is an object with an unapply method which takes an object and tries to give back its arguments.

As we all know that apply method of an Object takes arguments and creates an object and the unapply method will do the reverse.

Lets see this with an example.



object Customer {

  def apply(firstName: String, lastName: String) = firstName + "," + lastName

  def unapply(customerName: String): Option[String] = {
    val nameArray = customerName.split(",")
    if (nameArray.nonEmpty) nameArray.headOption else None
  }

  def main(args: Array[String]): Unit = {
    val customer = Customer("Balachandar", "Kuppusamy")

    customer match {
      case Customer(name) => println(s"FirstName is:$name")
      case _ => println("Could not extract Name")
    }
  }
}


In the above code, Customer is an object and the apply method takes first and last names and combine those names with a comma symbol and the unapply method takes the name and split it and then return the first name as an output.

Customer(“Balachandar”, “Kuppusamy”) is a shorthand for calling Customer.apply(“Balchandar”, “Kuppusamy”) and case Customer(name) is a shorthand for calling Customer.apply(name).

The output of the above program will look like below,


FirstName is:Balachandar


ScalaTest

ScalaTest is a testing tool in the Scala eco system. Using this, we can test Java and Scala code effectively. Its very easy to use and it follows Behavior Driven Development(BDD).

In this post, we are going to see the usage of ScalaTest with an example.

Refer the below Scala Object “Operation”. This object contains methods to perform various mathematical operation.

Operation

Now let’s write a test class with the ScalaTest tool. Refer below the list of steps to be done to write a test class.

1. Create a test class and extend FunSpec class.
2. Then use describe and it to structure the test class and write the necessary tests.

Refer below the sample test class to test all the methods of “Operation” object.

OperationSpec

When we run the above test, the Run screen will look like below,

RunScreen