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 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

 

 

 

 

Scala List

In this post, we are going to see how we can merge two lists, append/prepend an element to a list.

We have various functions available to play with Scala List.

1. ::: or ++ operator to join two lists.
2. :+ and +: operators are used for append/prepend a value to a list(This will return a new list instance)


object Scala {

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

    //With ::: operator
    val list1 = List(1, 2, 3)
    val list2 = List(4, 5, 6)

    val joinList1 = list1 ::: list2
    println("joinList1::" + joinList1)


    //With ++ operator
    val joinList2 = list1 ++ list2
    println("joinList2::" + joinList2)


    //To append a value to an existing list use :+
    val appendList = list2 :+ 7
    println("appendList::" + appendList)


    //To prepend a value to an existing list
    val prependList =  3 +: list2
    println("prependList::" + prependList)

  }

}


The output is given below,


joinList1::List(1, 2, 3, 4, 5, 6)
joinList2::List(1, 2, 3, 4, 5, 6)
appendList::List(4, 5, 6, 7)
prependList::List(3, 4, 5, 6)