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.

Syntax:

    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.")
        }
        else
            Left(number + " is not even.")
    }
    
    // main code
    def main(args: Array[String]) {
        println(isEven(4))
        println(isEven(95))
    }
}

Output

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


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.