In Scala Either, functions exactly similar to an Option. The only dissimilarity is that with Either it is practicable to return a string which can explicate the instructions about the error that appeared. The Either has two children which are named as Right and Left where, Right is similar to the Some class and Left is same as None class. Left is utilized for the failure where, we can return the error occurred inside the child Left of the Either and Right is utilized for Success.
Example:
Either[String, Int]
Here, the String is utilized for the Left child of Either as its the left argument of an Either and Int is utilized for the Right child as its the right argument of an Either. Now, let’s discuss it in details with the help of some examples.
-
Example :
object GfG extends App
{
def Name(name : String) : Either[String, String] =
{
if (name.isEmpty)
Left( "There is no name." )
else
Right(name)
}
println(Name( "GeeksforGeeks" ))
println(Name( "" ))
}
|
Output:
Right(GeeksforGeeks)
Left(There is no name.)
Here, isEmpty method checks if the field of name is empty or filled, if its empty then Left child will return the String inside itself and if this field is not empty then the Right child will return the name stated.
-
Example :
object either extends App
{
def Division(q : Int, r : Int) : Either[String, Int] =
{
if (q == 0 )
Left( "Division not possible." )
else
Right(q / r)
}
val x = Division( 4 , 2 )
x match
{
case Left(l) =>
println( "Left: " + l)
case Right(r) =>
println( "Right: " + r)
}
}
|
Here, the division is possible which implies success so, Right returns 2. Here, we have utilized Pattern Matching in this example of Either.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
17 Apr, 2019
Like Article
Save Article