1. Introduction

Scala offers various mechanisms for managing the absence of a value or potential errors, including Try, Either, and Option. Occasionally, we need to convert between these types to manage specific scenarios or interact effectively with APIs.

In this tutorial, we’ll look at different methods for converting an Option type to an Either type.

2. Option and Either

Option[T] is a container type designed to contain either a value of type T or no value. Some[T] signifies the presence of a value of type T, while None indicates its absence within the Option. This feature effectively prevents null pointer exceptions.

Either[L, R] represents a value of one of two possible types: Left[L] or Right[R]. Conventionally, the Left represents a failure or error case, while the Right denotes a successful computation result.

3. Converting an Option to Either

In this section, we’ll explore various methods for converting an Option into an Either value. While Option represents the potential presence or absence of a value, Either typically signifies one of two outcomes: a successful value or an error case. Therefore, when converting an Option to an Either, we must explicitly provide an additional value, often representing a failure scenario if the Option is empty. For this tutorial, let’s define a specific error value to use:

sealed trait Error
case object EmptyOptionValue extends Error

While any type can represent a failure case, using an enum or a sealed trait is advisable to define the potential errors. This practice enhances code clarity and maintainability by explicitly defining all possible error states.

Scala offers multiple approaches to perform these conversions.

3.1. Using if-else

We can use a simple if-else condition to convert an Option to an Either:

def usingIfElse(option: Option[String]): Either[Error, String] = {
  if (option.isDefined) Right(option.get) else Left(EmptyOptionValue)
}
val either = usingIfElse(Option("Baeldung"))
either shouldBe Right("Baeldung")
val left = usingIfElse(None)
left shouldBe Left(EmptyOptionValue)

Here, we used the Right() and Left() builder methods based on the if condition.

3.2. Using Pattern Matching

Alternatively, we can apply pattern matching on the Option and convert it to an Either:

def usingPatternMatch(option: Option[String]): Either[Error, String] = {
  option match {
    case Some(value) => Right(value)
    case None        => Left(EmptyOptionValue)
  }
}

This method offers both flexibility and readability when handling conversions.

3.3. Using Option.toRight()

The Option class provides a convenient conversion method through toRight():

def usingToRight(option: Option[String]): Either[Error, String] = {
  option.toRight(EmptyOptionValue)
}

The toRight() method retrieves the value from the option and assigns it to the right side of the Either. If the option is empty, it applies the provided value to the left side.

3.4. Using Either.cond()

Either offers a builder method for generating an Either value based on a predicate:

def usingCond(option: Option[String]): Either[Error, String] = {
  Either.cond(option.nonEmpty, option.get, EmptyOptionValue)
}

The cond() function accepts three parameters: first, the predicate function; second, the value to apply if the predicate is true; and finally, the value to apply when the predicate is false. This function is helpful as it enables the creation of Either values from any predicate function in a concise yet expressive manner.

3.5. Using fold()

Alternatively, we can use the very powerful fold() function to convert an Option to an Either:

def usingFold(option: Option[String]): Either[Error, String] = {
  option.fold(Left(EmptyOptionValue))(Right(_))
}

We use Left(EmptyOptionValue) as the initial value within the fold() function.

3.6. Using map()

Similar to other container types in Scala, Option supports the map() function for transformation into Either:

def usingMap(option: Option[String]): Either[Error, String] = {
  option.map(Right(_)).getOrElse(Left(EmptyOptionValue))
}

The getOrElse() function is applied to the transformed option to manage converting the empty value to the Left.

4. Conclusion

In this article, we explored various ways to convert an Option value into an Either value. We can choose the optimal approach depending on the specific scenario and personal preference.

As always, the sample code used in this article is available over on GitHub.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments