Either
In most functional programming languages, there is a type called Either (or a synonym). The Either
type is used to represent a value that can have two possible types. It is common to see Either
used to represent a success value or a failure value, although that doesn't have to be the case.
Although Kotlin doesn't come with an Either
as part of the standard library, it's very easy to add one.
Let's start by defining a sealed abstract class with two implementations for each of the two possible types that Either
will represent:
sealed class Either<out L, out R> class Left<out L>(value: L) : Either<L, Nothing>() class Right<out R>(value: R) : Either<Nothing, R>()
It is usual to call the two implementations Left
and Right
. By convention, when Either
class is representing success or failure, the Right
class is used for the success type.
Fold
The first function we'll add to Either
is the fold
operation. This will accept two functions...