Functional Programming in Kotlin(Part-1) Higher-Order Functions

I hope it was that easy when I first googled the term functional programming or FP for short. I struggled across various articles and blogs to understand FP and, I am still learning how it works by using it every day in my code.

Before we understand functional programming lets see how non-functional programming works.

I know many readers might skip this section, thinking they know what is non-functional programming as they wake up in the morning go to their offices sit in their chair and stare at the face of it.

But If you care to read it, I’ll tell you a basic difference between FP and non-FP (of course the later uses ‘ non ‘ as a prefix. Duh!). When we talk about non-FP or Imperative programming.

Let’s assume you are given a task to create a simple code in swift to sort an array of string, how would you do it?

Now you will think this is what we do when we write a program in any language, we create some literals that act as constants and some variables that tend to change their state as the program proceeds.

But do we ever think that using variables have some side effects when it comes to multi-threading environment?
Often while we write a program we come across a situation when we need to take care of multiple threads accessing a function and mutating the state of variable resulting wrong output. What if I say we can overcome this so called ‘side-effect’ using functional programming.

In this first part of the series, I will begin by telling you about one of the most important concepts in functional programming and that is Higher-Order Functions.

I will talk about what higher-order functions are and I will then move on to code and show you how to use them.

Functional programming has made programming so much more fun to me. If you have been programming for a while but haven’t yet tried your hand at functional programming before, this series is going to change your life. Learning to program functionally is gonna make you so much a better programmer you will feel much more secure with the quality of your work and it will be a lot better and you will be more sought after. You will be able to write your programs with fewer bugs in less time. Your code will have fewer bugs because your code will be easier to reason about and you will be able to write it in less time because you will be able to reuse more of your code.

So let me tell you about higher-order functions because that is going to make me feel Super Smart.

In Kotlin and in all functional programming languages functions are values. Let me show you what I mean by that. Here we will see the basic function in its natural habitat.

fun triple(x: Int) : Int{
return x*3

So you will recognize this even if you don’t know Kotlin because all other programming languages have functions, but not all programming languages can do like below code, create an anonymous function and assign it to a variable just like any other value.

var triple = fun (x: Int) : Int{
return x*3
var waffle = triplewaffle(30)

You know? … Yes this will be 90

Again! in functional programming languages functions are values just like strings or numbers functions can be assigned to variables or pass into other functions, higher-order functions, but what are higher-order functions good for?… composition. The fact that we can take one function and put it into another function allows us to compose a lot of small functions into bigger functions.

That’s all a lot of theory. Let’s look at how to actually use one of these things. Probably the most basic and useful higher-order function is filter, It’s really simple. Filter is a function on the array that accepts another function as its argument which it will use to return a new filtered version of the array.

Here we see a list of animals and we want to filter out dogs.

I am going to show you how to do this using filter, but before I do I want to remind you how you do this with a normal for Loop.

var dogs = arrayListOf<Animals>()
for (animal in animals) {
if (animal.species=="dog")

So this is just an ultra normal for loop it creates an ArrayList to hold the dogs. It iterates over the animal ArrayList and if the species of the animal is being iterated is equal to dog it will add that dog onto the animals ArrayList.

Now let’s rewrite this using the filter function.

var dogs = animals.filter(fun(animal): Boolean {
return animal.species == "dog"

So let’s have a look at this, filter accepts one argument another function. Functions that you send into other functions are called Callback functions because the host function will call back to them. Filter will loop through each item in the array and for each item it’s going to pass it into the callback function and when it does it will expect the callback function to return either true, or false to tell filter whether or not this item should be in the new array and after it’s done, It will return the new filtered array, and that will be dogs.

Remember how I said that You’ll write software faster when you’re doing functional programming. Notice here that the example that uses filter is a lot less code than the for loop and That is not because the syntax is cosmetically shorter or anything it’s because we’re actually writing less code, less logic.

The reason that we need less logic is that when we write our software in small simple functions. They compose together which allows us to reuse functions all over the place. So in the filter example. We are just writing one line of logic really. The callback function and the filter function just slopped into each other. They are Composable. I’d really like to stress how well these simple functions compose.

Let’s break out the callback into a separate variable.

var isDog = fun(animal: Animals): Boolean {
return animal.species == "dog"
var dogs = animals.filter(isDog)

So notice here that is the dog is just a function that checks that an object is a dog. It doesn’t really have anything to do with the filtering at all. It’s completely decoupled from it, so we can use it for other things. For instance, if we wanted the animals that aren’t dogs, we could pass it to filterNot which is another a higher-order function on the array object that does the inverse of the filter so it could be animals that aren’t dogs.

Let’s see how this looks.

var otherAnimals = animals.filterNot(isDog)

You see that we very cleanly broken the problem up into two completely separate problems, the problem of determining if an animal is a dog or not, and the problem of creating an array and stuffing the objects into them, and this way we’re allowed to think and reason and debug these problems separately and that is a lot easier than when the two solutions are all jumbled together like in the for loop.

Today, I’ve talked about how functional programming means that you can write software with fewer bugs in less time. In Kotlin, functions are values and you can exploit this by dividing your code into small simple functions and composing them together using higher-order functions. As an example, I showed you the higher-order function filter and how it compares to normal for loop.

We’re just scratching the surface here. Learning functional programming is going to introduce you to a whole new world that you didn’t know existed. There are many useful higher-order functions besides filter next time I will talk about two of the map and reduce.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Key Differences Between NoSQL & SQL : MySQL & MongoDB

AWS-Compute As a Service : EC2

Git-Pong — Collaborating using version control

Working with XML tree data in Python

State of CSS 2020: Layout Resources

Activate PythonVirtual Environment with batch Script-Windows

Optimizing AWS Java Lambdas

CS 371p: Final Entry

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kiran Choudhary

Kiran Choudhary

More from Medium

Annotations, Unions, and Aliases in TypeScript

Continuous Sub Array Sum (Leet Code)

Python: Everything is an object

The Darker Side of learning How to Code