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.


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


The output is given below,


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

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