Scala Either Keyword with Example

Scala | Either Keyword: Here, we are going to learn about the Either keyword with its usages, syntax and example in Scala?
Submitted by Shivang Yadav, on May 14, 2020

Scala | Either Keyword

Either is a container similar to the option which has two values, they are referred to as children. The left and right children are named as the right child and left child.

The left child is similar to None class which is used when there can be an error returned.

The right child is similar to Some class which is used when a vale is to be returned i.e. for the successful execution of code.


    Either [left, right]

Both left and right are data types of the returned values which can be used to define the results when there are error case or valid case.

Example to understand the working of Either Keyword

object MyObject {
    // function defintion
    def isEven(number : Int ): Either[String, String] = {
        if(number%2 == 0){
            Right(number + " is even.")
            Left(number + " is not even.")
    // main code
    def main(args: Array[String]) {


Right(4 is even.)
Left(95 is not even.)

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.