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 ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.