Instruction

Higher-Order Functions

A higher-order function is a function that can take functions as parameters or return a function. This lets you pass specific behavior to a function, making it more flexible and reusable.

In addition to passing String or Int as parameters to a function, for instance, you can also pass lambda expressions. Consider the following code:

fun applyOperation(
    num: Int,
    // 1
    operation: (Int) -> Int): Int {
  val result = operation(num1)
  println("Result afer applying operation: $result")
  return result
}
  1. applyOperation() is a higher-order function because it takes another function, operation, as a parameter.

You also can pass lambdas that return Unit to other functions like this:

fun sendMessage(message: String, logMessage: (String) -> Unit) {
  logMessage(message)
  println("Sending message....")
}

Higher-order functions are super useful in scenarios where you want to customize some behavior that happens within a function. The example above is one example of such behavior, where you may want to have custom logging behavior depending on where you’re calling the sendMessage function from. If you’re calling it from a debug environment you might just want to print the message to the screen. If you’re instead calling it from a production environment you might want to save the message to a log file.

You’ve learned a bit about higher-order functions. Next, you’ll dive into practical examples that will show you how to put this knowledge into action.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo