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

Validation and error accumulation


To round up our introduction to functional programming, we'll cover another common pattern, that of error accumulation. This is also sometimes simply referred to as validation.

The idea is that we have a series of functions that individually error check a value. They can return some kind of success value if the input is good, and some kind of error value if the input is bad. These individual functions are then combined, retaining all the errors (if any). Finally, we can interrogate the accumulation to get the errors.

Let's start by modeling the good and bad values that we can use. We'll call these Valid and Invalid, respectively. They will both extend from a superclass called Validation:

    sealed class Validation 
    object Valid : Validation() 
    class Invalid(val errors: List<String>) : Validation() 

Note that the Invalid case contains a list of errors in the form of strings, and each successive error will be added to this. This...