Saturday, November 16, 2024
Google search engine
HomeGuest BlogsKotlin Higher-Order Functions

Kotlin Higher-Order Functions

Kotlin language has superb support for functional programming. Kotlin functions can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions. 

Higher-Order Function –

In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience. 

Passing lambda expression as a parameter to Higher-Order Function –

We can pass a lambda expression as a parameter to Higher-Order Function. 
There are two types of lambda expression which can be passed- 

  • Lambda expression which return Unit
  • Lambda expression which return any of the value integer,string etc

Kotlin program of lambda expression which returns Unit-  

Kotlin




      // lambda expression
var lambda = {println("neveropen: A Computer Science portal for Geeks") }
      // higher-order function
fun higherfunc( lmbd: () -> Unit ) {     // accepting lambda as parameter
    lmbd()                               //invokes lambda expression
}
fun main(args: Array<String>) {
     //invoke higher-order function
    higherfunc(lambda)                 // passing lambda as parameter
}


Output: 

neveropen: A Computer Science portal for Geeks

Explanation: 
Let’s understand the above program step by step:
In the top, we define a lambda expression which contains print() to print string to the standard output. 

var lambda = {println("neveropen: A Computer Science portal for Geeks") } 

then, we define a higher-order function which contains one parameter. 

lmbd: () -> Unit

lmbd is local name for the receiving lambda parameter. 
() represents that the function does not accept any arguments. 
Unit represents that function does not return any value.
In main function, we have invoked the higher-order function by passing the lambda expression as parameter. 

higherfunc(lambda)

Kotlin program of lambda expression which returns Integer value –  

Kotlin




    // lambda expression
var lambda = {a: Int , b: Int -> a + b }
    // higher order function
fun higherfunc( lmbd: (Int, Int) -> Int) {      // accepting lambda as parameter
         
    var result = lmbd(2,4)    // invokes the lambda expression by passing parameters                   
    println("The sum of two numbers is: $result")
}
 
fun main(args: Array<String>) {
    higherfunc(lambda)           //passing lambda as parameter
}


Output: 

The sum of two numbers is: 6

Explanation: 
Let’s understand the above program step by step:
In the top, we define a lambda expression defined which returns Integer value. 

var lambda = {a: Int , b: Int -> a + b }

Then,we have defined higher-order function which accepts the lambda expression as parameter.  

lmbd: (Int, Int) -> Int

lmbd is local name for the receiving lambda parameter. 
(Int,Int) represents that function accepts two integer type parameters. 
-> Int represents that function returns an integer value.
In main function, we have invoked the higher-order function by passing the lambda as parameter. 

higherfunc(lambda)

Passing function as a parameter to Higher-Order function –

We can pass a function as a parameter in Higher-Order function. 
There are two types of functions which can be passed- 

  • function which return Unit
  • function which return any of the value integer, string etc

Kotlin program of passing function which returns Unit-  

Kotlin




    // regular function definition
fun printMe(s:String): Unit{
    println(s)
}
   // higher-order function definition
fun higherfunc( str : String, myfunc: (String) -> Unit){
   // invoke regular function using local name
    myfunc(str)
}
fun main(args: Array<String>) {
    // invoke higher-order function
    higherfunc("neveropen: A Computer Science portal for Geeks",::printMe)
}


Output: 

neveropen: A Computer Science portal for Geeks

Explanation: 
In the top, we define a regular function printMe() which accepts a parameter of String type and return Unit. 

fun printMe(s:String): Unit

(s: String) is the only parameter 
Unit represents the return type
Then, we define the Higher-order function as 

fun higherfunc( str : String, myfunc: (String) -> Unit)

it receives two parameters one is String type and another one is function 
str: String represents string parameter 
myfunc: (String) -> Unit represents that it accept function as a parameter which returns Unit.
From main function, higher function is invoked by passing the string and function as arguments. 

 higherfunc("neveropen: A Computer Science portal for Geeks",::printMe)

Kotlin program of passing function which returns integer value- 

Kotlin




    // regular function definition
fun add(a: Int, b: Int): Int{
    var sum = a + b
    return sum
}
    // higher-order function definition
fun higherfunc(addfunc:(Int,Int)-> Int){
    // invoke regular function using local name
    var result = addfunc(3,6)
    print("The sum of two numbers is: $result")
}
fun main(args: Array<String>) {
    // invoke higher-order function
    higherfunc(::add)
}


Output: 

The sum of two numbers is: 9

Explanation: 
In the top, we define the regular function as 

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

it accepts two parameters of Integer type, and return the sum of both the integers
Then, we define the higher-order function as 

fun higherfunc(addfunc:(Int,Int)-> Int)

it accepts a function which contains two parameters and 
call the regular function addfunc(3,6) by passing the parameters.
From main function, we invoke the higher-order function by passing the regular function as parameter 

higherfunc(::add)

Returning a function from Higher-Order function

We can return a function from higher-order function. While returning the function, we have to specify the parameter types and return type of regular function in the return type of the higher-order function. 

Kotlin program of a function returning another function-  

Kotlin




      // function declaration
fun mul(a: Int, b: Int): Int{
    return a*b
}
    //higher-order function declaration
fun higherfunc() : ((Int,Int)-> Int){
    return ::mul
}
fun main(args: Array<String>) {
     // invoke function and store the returned function into a variable
    val multiply = higherfunc() 
    // invokes the mul() function by passing arguments
    val result = multiply(2,4)  
    println("The multiplication of two numbers is: $result")
}


Output: 

The multiplication of two numbers is: 8

Explanation: 
In the top of program we define mul() function which accepts two parameters and its return type is also an integer. 

fun mul(a: Int, b: Int): Int

Then, we define the higher-order function having return type is a function. 

fun higherfunc5() : ((Int,Int)-> Int){
    return ::mul
}

::mul represents that it return mul() function 
(Int,Int) represents that mul accepts two integer type parameters 
Int represents that mul returns an integer value.
In main function, we have called the higher function which returns another function and store this in a variable multiply . 

val multiply = higherfunc()

then we invoke the mul() function using local variable multiply(2,4) by passing two arguments.
 

Last Updated :
14 Apr, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Recent Comments