Open In App

How to Pass a Function as a Parameter to Another in Kotlin?

Improve
Improve
Like Article
Like
Save
Share
Report

Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters. This is an extremely useful feature and makes our code much easier to work with. In fact, many of the Kotlin library’s functions are high order, such as NBQ. In Kotlin, we can declare functions and function references as values that are then passed into the function. We will first understand how to declare lambdas and then how to pass them into a function.

Example

Let’s start by understanding how we declare functions as lambdas:

Kotlin




fun main (args: Array<String>) {
  val funcMultiply - {a: Int, b: Int -> a*b}
  println (funcMultiply (4, 3))
  val funcSayHi - {name: String -> println ("Hi $name") }
  funcSayHi("John")
}


In the preceding code block, we declared two lambdas: one (funcMultiply) that takes two integers and returns an integer, and another (funcSayHi) lambda that takes a string and returns a unit-that is, it returns nothing. Although we did not need to declare the type of arguments and the return type in the preceding example, in some cases we need to explicitly declare the argument types and return types. We do this in the following way:

Kotlin




fun main (args: Array<String>) {
  val funcMultiply : (Int, Int)->Int = {a: Int, b:Int -> a*b}
  println (funcMultiply (4, 3))
  val funcSayHi : (String) ->Unit = {name: String -> println("Hi $name")}
  funcSayHi ("John")
}


So now that we have a general idea of how lambdas work, let’s try and pass one in another function-that is, we will try a high-order function. Check out this code snippet:

Kotlin




fun main (args: Array<String>) {
  val funcMultiply : (Int, Int) ->Int = {a: Int, b:Int -> a*b}
  val funcSum : (Int, Int) ->Int = {a: Int, b: Int -> a+b}
  performMath (3, 4, funcMultiply)
  performMath (3, 4, funcSum)
}
 
fun performMath (a: Int, b:Int, mathFunc : (Int, Int) -> Int) : Unit
{
  println ("Value of calculation: ${mathFunc (a, b) }")
}


It is as simple as that-create a function lambda and pass it into the function. So this is just one aspect of a high-order function-that is, we can pass a function as an argument to the function. Another use of high-order functions is to return a function. Consider the following example where we need a function that transforms the total price of an order according to certain conditions. Kind of like an e-commerce site, but way simpler

Kotlin




fun main(args: Array<String>) {
  // free delivery of order above 499
  val productPricel = 600;
  // not eligible for free delivery
  val productPrice2 = 300;
  val totalCost1 = totalCost (productPrice1)
  val totalCost2 = totalCost (productPrice2)
   
  println("Total cost for item 1 is ${totalCost1 (productPrice1) }")
  println ("Total cost for item 2 is ${totalCost2 (productPrice2) }")
}
 
fun totalCost (productCost : Int) : (Int) -> Int(
  if (productCost > 499) {
    return { x -> x }
  }
  else {
    return { x -> x + 50 }
  }
}


Note how we need to change functions that we apply based on certain conditions so that we return a function that suits the conditions. We assign the returned function to a variable and then we can just put append () in front of the variable to use it as a function, just like we did with the lambdas. This works because the high-order function is essentially returning a lambda.

In Kotlin, we can assign a function to a variable, and then we can pass it into a function or return it from a function. This is because it’s essentially declared like a variable. This is done using a lambda declaration of functions.



Last Updated : 11 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads