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

What is functional programming?


Functional programming is a paradigm (a style of structuring your programs). In essence, the focus is on transforming data with expressions (ideally such expressions should not have side effects). Its name, functional, is based on the concept of a mathematical function (not in sub-routines, methods, or procedures). A mathematical function defines a relation between a set of inputs and outputs. Each input has just one output. For example, given a function, f(x) = X2; f(5) is always 25.

The way to guarantee, in a programming language, that calling a function with a parameter always returns the same value, is to avoid accessing to mutable state:

fun f(x: Long) : Long { 
   return x * x // no access to external state
}

The f function doesn't access any external state; therefore, calling f(5) will always return 25:

fun main(args: Array<String>) {
    var i = 0

    fun g(x: Long): Long {
       return x * i // accessing mutable state
    }

    println(g(1))...