Higher-Order Functions and Lambdas in Kotlin

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
Higher-Order Functions and Lambdas in Kotlin

I am Amit Shekhar, Co-Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Join Outcome School and get high paying tech job: Outcome School

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

This article is for anyone who is curious about the higher-order functions and lambdas in Kotlin but has no idea what they are exactly.

My goal is to make you understand what are higher-order functions and lambdas which means that there are few simplifications done while writing this. If you understand what higher-order functions and lambdas in Kotlin are, then my mission will be accomplished.

Let's start with the Lambda Expressions and understand what they are.

Lambdas Expressions

Lambdas Expressions are essentially anonymous functions that we can treat as values – we can, for example, pass them as arguments to functions, return them, or do any other thing we could do with a normal object.

Lambda Expressions look like below:

val square : (Int) -> Int = { value -> value * value }
val nine = square(3)

Now, let's learn it by a simple example in Kotlin:

val doNothing : (Int) -> Int = { value -> value }

This is a lambda expression that does nothing. Here the

{ value -> value } is a complete function in itself. It takes an int as a parameter and returns a value as an int.

In (Int) -> Int

(Int) represents input int as a parameter.

Int represents return type as an int.

So, the doNothing is a function in itself that takes a value as an int and returns the same value as an int.

Now another example:

val add : (Int, Int) -> Int = { a, b -> a + b }

This is also a lambda expression that takes two int as the parameters, adds them, and returns as an int.

{ a, b -> a + b } is a function in itself that takes two int as the parameters, adds them, and returns as an int.

In (Int, Int) -> Int

(Int, Int) represents two int as the input parameters.

Int represents return type as an int.

So, the add is a function in itself that takes two int as the parameters, adds them, and returns as an int.

We can call it very similar as we do with the function like below:

val result = add(2,3)

Now, that we have understood the lambda expressions. Let's move to the Higher-order functions.

Higher-Order Functions

A higher-order function is a function that takes functions as parameters or returns a function.

It's a function that can do at least one of the following:

  • Can take functions as parameters
  • Can return a function

We will see both the thing one by one.

Let's start with the first one - A function can take functions as parameters.

fun passMeFunction(abc: () -> Unit) {
  // I can take function
  // do something here
  // execute the function
  abc()
}

This takes a function abc: () -> Unit

abc is just the name for the parameter. It can be anything. We just need to use this when we execute the function.

() -> Unit, this is important.

() represents that the function takes no parameters.

Unit represents that the function does not return anything.

So, the passMeFunction can take a function that takes zero parameters and does not return anything.

Let try passing that type of function to the passMeFunction.

passMeFunction(
        {
          val user = User()
          user.name = "ABC"
          println("Lambda is awesome")
        }
)

Here { } is a function in itself. See below highlighted one.

passMeFunction(
         {
           val user = User()
           user.name = "ABC"
           println("Lambda is awesome")
         }
)

Which takes zero parameters and does not return anything. It just creates a user, set the name, and print something. This means it does not take any parameters and does not return anything.

Let's add fun abc() just for the sake of understanding it. Actually, we do not need to write fun abc() in our code. It is just for understanding purpose now.

passMeFunction(
fun abc(){
           val user = User()
           user.name = "ABC"
           println("Lambda is awesome")
         }
)

Now, we can clearly see that we are passing a function to the passMeFunction.

As Kotlin provides us a concise way for writing code, it can be changed to the following by removing the ().

passMeFunction {
  val user = User()
  user.name = "ABC"
  println("Lambda is awesome")
}

Now, that we have understood how to pass a function as a parameter to a function.

Let's move to the second one - A function can return a function.

A function can return a function

Suppose we have a function add which takes two parameters and returns a value as in int.

fun add(a: Int, b: Int): Int {
  return a + b
}

And, we have a function returnMeAddFunction which takes zero parameters and returns a function of the type ((Int, Int) -> Int).

fun returnMeAddFunction(): ((Int, Int) -> Int) {
   // can do something and return function as well
   // returning function
   return ::add
}

((Int, Int) -> Int)

(Int, Int) means that the function should take two parameters both as the int.

Int means that the function should return value as an int.

Now, we can call the returnMeAddFunction, get the add function, and call it like below:

val add = returnMeAddFunction()

val result = add(2, 2)

This is what higher-order functions are.

I hope you understood "What are Higher-Order Functions and Lambdas in Kotlin?"

Show your love by sharing this blog with your fellow developers.

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar
Co-Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.