Scala Either

Either, you will see, is kind of a in-betweenTryandOption.

Try to experiment to see the similarity and differences.

Similar toOption, you can createEitherin two ways:

  • Rightwhich would be similar toSome
  • Leftwhich, over time, became similar toNone, except you can store information. I am saying “over time” because up until Scala v2.12+,Eitherwas notRight-bias.LeftandRightwere just two Types. But now,Leftis accepting to carry error messages andRightto be the channel for successes.

You can test which Type isEitherusingisLeftandisRight. You can also usemap,flatMap, etc… once again. You must be starting to know those functions pretty well by now. This is where theRight-biascome into play.mapwill take a function that modify the type contained inRightand will not do anything if theEithercontains aLeft.

If you would like to specifically act onLeftorRight, you can use the.leftand.rightmethods to project theEitheron one side of the other. For instance, to modify the content of theLeftwhen it is there, you can do.left.map(...).

One major difference withTryis thatEitherwill not catch the Exception. If an exception is thrown inside anEitherit will propagate. Inside aTryit will be captured inside theFailurechannel.

Reveal more information and clues
Load Exercise