🔴 Scala Beginner

What is the Either type in Scala?

Answer

Either[L, R] represents a value of one of two possible types. By convention, Left contains an error/failure and Right contains a success value (mnemonic: "right" = correct). def parseAge(s: String): Either[String, Int]. Return: Right(42) or Left("Invalid number"). Working with Either: pattern match: result match { case Right(age) => ...; case Left(err) => ... }. map: transforms Right, passes Left through. flatMap: chains computations. getOrElse: extract Right or use default. Either is used for error handling when you want to carry error information (unlike Option which only indicates absence). It is right-biased in Scala 2.12+ — map and flatMap operate on the Right side, enabling for-comprehension chaining of fallible operations.