Skip to content
Search

Scala:Either

lastmod 2020-08-27created 2020-08-272 edits

A type that can hold one of two values.

Putting a value in Either

The example shows how to put an Option into an Either.

def eitherTest(num: Option[Int]): Either[String, Int] = num match {
  case Some(n) => Right(n)
  case None => Left("Error! Number is missing!")
}

eitherTest(Some(7))
  • If a valid value is passed as the argument, it goes into Right, i.e. the right side of the Either;
  • if no valid value is passed as the argument, the value goes into Left, i.e. the left side of the Either.

Using an Either value

val res = eitherTest(Some(7))
if( res.isRight ) 
    println("Number is %s".format(res.right.get))
else if( res.isLeft) 
    println("Error message => %s".format(res.left.get))

In the code above, the value res returned by calling the eitherTest method is of type Either[String, Int], and res.isRight and res.isLeft are used to check which side holds the valid value.

Using pattern matching

val result = eitherExample(Some(7)) match {
  case Right(num) => num
  case Left(err) => err
}

See also

Favorite site

author Zer0 sitemap