Book Image

Functional Kotlin

Book Image

Functional Kotlin

Overview of this book

Functional programming makes your application faster, improves performance, and increases your productivity. Kotlin supports many of the popular and advanced functional features of functional languages. This book will cover the A-Z of functional programming in Kotlin. This book bridges the language gap for Kotlin developers by showing you how to create and consume functional constructs in Kotlin. We also bridge the domain gap by showing how functional constructs can be applied in business scenarios. We’ll take you through lambdas, pattern matching, immutability, and help you develop a deep understanding of the concepts and practices of functional programming. If you want learn to address problems using Recursion, Koltin has support for it as well. You’ll also learn how to use the funKtionale library to perform currying and lazy programming and more. Finally, you’ll learn functional design patterns and techniques that will make you a better programmer.By the end of the book, you will be more confident in your functional programming skills and will be able to apply them while programming in Kotlin.
Table of Contents (22 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Index

Option


The Option<T> datatype is the representation of a presence or absence of a value T. In Arrow, Option<T> is a sealed class with two sub-types, Some<T>, a data class that represents the presence of value T and None, and an object that represents the absence of value. Defined as a sealed class, Option<T> can't have any other sub-types; therefore the compiler can check clauses exhaustively, if both cases, Some<T> and None are covered.

I know (or I pretend to know) what you're thinking at this very moment—why do I need Option<T> to represent the presence or absence of T, if in Kotlin we already have T for presence and T? for absence?

And you are right. But Option provides a lot more value than nullable types, let's jump directly to an example:

fun divide(num: Int, den: Int): Int? {
    return if (num % den != 0) {
        null
    } else {
        num / den
    }
}

fun division(a: Int, b: Int, den: Int): Pair<Int, Int>? {
    val aDiv = divide(a...