kotlin HigherOrder Function

Alok Verma
MindOrks
Published in
2 min readApr 27, 2019

Hello Guys!! I hope you all are doing well, this tutorial is going to very short more code less theory.

So, what makes kotlin special than java, one of its function which can accept a function as parameter or function can return a function or can do both.

For higher order function first, we need to understand lambda. Lambda expression functions without a name. example -

val print: (Int) -> Unit = { s: Int -> println(s) }

As you can see, I have defined a lambda same as we declare a variable in kotlin. I right side there are two curly braces which are basically our lambda, first is the parameter that we pass in a function and after arrow the body of the function, if we convert this lambda in a function the structure would be-

private fun print(var s:Int){
println(s)
}

This is a function that we have converted in lambda called print. So how to use this lambda in higher order function. Now we define a function that accepts lambda function as a parameter.

fun addTwoNumber(a: Int, b: Int, action: (Int) -> Unit) {
val s = a + b
action(s)
}

This function accepts three parameters a, b which are Int type and the third one is an action which is a function type that accepts a lambda whose type is (Int) -> Unit. This function adds two numbers and prints the result.

How to use this function is very simple, just pass a lambda to the calling function. What this lambda does, it just copies the body of lambda function to this function where we call it.

addTwoNumber(2, 4, print)

For calling addTwoNumber accept parameter print which we defined earlier as a lambda expression.

This example, I hope you guys can understand the basics of higher order function in kotlin and lambda expression.

Thanks,

Alok V.

--

--

Alok Verma
MindOrks

Sr. Software Engineer @OYO, Cinema fanatic, Technology enthusiast.