If you reach here after searching on google then there’s a might chance that you read this “Functional programming has a deep learning curve, not easy for beginner” But if you’ve been programming in Kotlin for a while, chances are good that you already use a lot functional programming concepts in your software.

Don’t let all the new words scare you away. It’s a lot easier than it sounds.

Functional programming has become a really hot topic in the programmer’s world. Many programming languages support programming in both functional and imperative styles; So does the Kotlin programming language. Kotlin offers almost all features to qualify for functional programming. In my opinion, it has all the support to become functional programming features like high-order functions, lamdas, Immutability, lazy evaluation, and recursion.

Functional programming makes code understandable by minimizing moving parts. Michael Feathers

What is Functional Programming?

Functional programming (often abbreviated as FP) is the process of building software by composing pure function, avoiding shared state, and mutable data. Functional programming is declarative rather than imperative, and the application state flows through pure functions.

Functional code tends to be more concise, more predictable, and easier to test than an imperative or object-oriented way of programming.

Features Of Function Programming in Kotlin

Higher-order functions

Kotlin has the higher-order function, which allows us to treat functions as data–assign them to a variable, pass them to other functions, return from functions, etc… A basic example of a higher-order function (HOF) is a map that takes a function of any given type (because of its generic utility), applied the function to all elements of the list, and return the list of its result.

I’d show you the complete example of how to write map function but I already wrote a complete article on map, filter, and lambda. So, here it is.

Higher-order functions are often used:

Take a list of functions and returns some composition of those input functions.

Are used to implement domain-specific languages.

Apply a function to its argument or create a curried function for those purposes of reuse or function composition.

Immutable data

An immutable object is an object that can’t be modified after it’s creation. The functional programs typically operate on immutable data. Instead of altering existing values, altered copies are created and the original is preserved. Since the unchanged parts of the structure cannot be modified, they can often be shared between the old and new copies, which saves memory.

In kotlin, we can make a truly immutable object with val keyword.

As you can see, the top-level primitive property y can’t be changed. Even if I try to change it the compiler shows me error val cannot be reassigned.

Note: In kotlin, it’s important not to confuse const with immutability. The const keyword variable is known at compile-time constant while on the other hand val is used to define constant at run time.

Roman Elizrov says this on twitter about Immutability val.

“Make val not var! (and your code will be pure). If you only use vals in your classes, then they are immutable and it is enforced. Pragmatically, the fewer vars you have in your code the better. Ideally, no vars at all.”

Pure Functions

A pure function takes some input and returns some output based on the input. They are the simplest reusable building blocks of code in the program. Pure functions in computer science are KISS (Keep It Simple, Stupid).

Like other pure functional programming languages, Kotlin compiler doesn’t enforce us to write pure functions. It is up to us to create pure functions and enjoys its benefits.

Here are some fundamental properties of pure function.

A function returns exactly the same result every time it’s called with the same set of arguments. In other words, a function has no state, nor it can access any external state. Every time we call it, it behaves like a newborn baby with a blank memory and no knowledge of the eternal world.

A function has no side effects. Calling a function once is the same as calling it twice and discarding the result of any function call.

They are easy to move around.

Pure functions have many beneficial properties as well as they are extremely independent. Their independence nature also makes them great candidates for parallel processing across may CPUs, and across entire distributed computing cluster.

Before showing you the example of a pure function in Kotlin I want you to read out this entire discussion on Kotlin Forum: Rationalizing Pure Function in Kotlin

Example of pure function in kotlin.

fun greetNewBorn(name: String) : String { return "Hello to new world -> $name" }

Lazy Evaluation

Some pure functional languages like Haskell provides a lazy (non-strict) evaluation mode. Kotlin, by-defaults, uses an eager (strict) evaluation. Kotlin doesn’t provide native support for lazy evaluation as part of the language itself but as part of Kotlin’s Standard Library and language feature named lazy delegated property.

I already wrote a three-part series on Kotlin Lazy Evaluation!

Exception Handling

Show me how you handle errors and I’ll tell you what programmer you are.

Error handling is one of the most important– and overlooked– topic of programmers, regardless of what language you are using. In kotlin, you’ll find two major types of error handling.

Exception handling with try/catch.

Exception handling with kotlin.runCatching.

Read “Functional Way of handling an error with Kotlin RunCatching” for more details.

In last I just want you to check out this Arrow-kt library. It is a functional companion tool-kit for Kotlin programming language.

Thank you for being here and keep reading…