Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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