Option to Either and back safely

Option to Either and back safely

Introduction

This little code snippet will help you convert an Option into an Either and back. This can be useful if you want to carry an error state when the Option is None. It is also intersting to look at it to learn more about Option and Either.

Code Snippet

Here is a bit of code to transform an Option into an Either and back:

object OptionHelper {
    implicit class OptionToEither[A](opt: Option[A]) {
        def asEither[ERR](err: => ERR): Either[ERR, A] = {
            opt match {
                case Some(v)   => Right(v)
                case None        => Left(err)
            }
        }
    }

    implicit class EitherToOption[A](ei: Either[_, A]) {
        lazy final val asOption: Option[A] = {
            ei match {
                case Right(v)   => Some(v)
                case Left(_)     => None
            }
        }
    }
}

to import it:

import OptionHelper._

Note that going from Either to Option is not advised since you are going to lose the Left side of the Either with the information it contains.

Play with it!

Give it a spin:

Or directly on Scastie.

Conclusion

You now know how to convert an Option into an Either and back. Use it wisely !

Leave a Reply

%d bloggers like this: