×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala Either Keyword with Example

By IncludeHelp Last updated : October 20, 2024

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

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

The right child

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.