Kotlin Higher-Order Functions

Learn via video courses
Topics Covered

Overview

Kotlin, a statically typed programming language (the variable type is known at compile-time rather than run-time), has gained significant attention in the software development community due to its powerful features such as higher-order functions and lambda expressions. Higher-order functions in Kotlin allow functions to be treated as first-class citizens, which means they can be assigned to variables, passed as arguments to other functions, and returned as results from functions.

Higher Order Functions Kotlin

Higher-order Kotlin functions are functions that can accept other functions as parameters and/or return functions as their results. The concept of higher order function is derived from functional programming principles and allows you to develop more concise, flexible, and reusable code.

There are two main aspects to higher-order functions Kotlin:

  • Functions as Parameters:
    Higher order functions can take other functions as parameters. These functions are sometimes referred to as "lambda parameters" or "function parameters". This allows you to encapsulate behaviour and pass it as a parameter. Lambdas or anonymous functions are commonly used as these function parameters.
  • Functions as Return Values:
    Higher order functions can also return functions as their results. This allows you to dynamically create and customize functions based on specific cases or inputs.

Syntax

ElementExplanation
funKeyword to declare a function.
higherOrderFunctionName of the function.
parameterName of the parameter that is a lambda expression.
:Colon used to indicate the type of the parameter.
(Type) -> ReturnTypeType of the lambda expression that takes a Type parameter and returns ReturnType.
ReturnTypeThe return type of the higher-order function.

Defining a Higher Order Function Kotlin

Let's see an example of a higher order function Kotlin that takes a lambda (a type of function) as a parameter:

Output of the above code:

  • The performOperation is a higher order function that takes two integers and a function as parameters. It applies the provided function to the integers and returns the result.
  • In the main function, a lambda expression subtract for subtraction is defined.
  • The performOperation function is then called with the values 8, 4, and the subtract function, resulting in the difference 8 - 4.
  • The difference is printed.

Calling a Higher-Order Function

You can use a higher order function Kotlin by calling it and passing a function (usually a lambda) as an argument. For example:

Output of the above code:

  • The performOperation function is similar to the previous example. It takes two integers and a function as parameters.
  • In the main function, the performOperation function is called with the values 55, 33, and a lambda expression that performs multiplication.
  • The result of the multiplication is printed.

Trailing Lambda

When the last argument of a function is a lambda, you can move the lambda outside the parentheses for improved readability. Here's an example of performing this:

Output of the above code:

  • The performOperation function remains the same, taking two integers and a function as parameters.
  • In the main function, the performOperation function is called with the values 1010, and 22, and a trailing lambda expression that performs division.
  • The result of the division is printed.

"it" Keyword

The it keyword is a shorthand for referring to a single parameter in a lambda. It's especially useful when the lambda takes only one parameter. Here's an example of performing this:

Output of the above code:

  • The performOperation function now takes only one integer and a function as a parameter.
  • In the main function, the performOperation function is called with the value 55 and a lambda expression that calculates the square of a number using the it keyword.
  • The squared value is printed.

Assigning Null as the Default Value

You can provide a default value of null for a function parameter, including a lambda. If the caller doesn't provide a specific lambda, the default one will be used. For example:

Output of the above code:

  • The performOperation function now includes a default value for the operation parameter, allowing the function to be called without providing a custom operation.
  • In the main function, the performOperation function is called twice: once without providing a custom operation and once with a custom subtraction operation.
  • The results of both calls are printed.

Passing Lambda Expression as A Parameter to Higher Order Function Kotlin

Lambda expressions, often known as anonymous functions, provide a short syntax for defining functions that do not require explicit function names. They are ideal for short, single-purpose functions. In Kotlin, lambda expressions are surrounded by curly braces {}, and parameters are specified before the -> arrow

Example:

Consider the scenario where you have a higher order function Kotlin called performOperation that takes two parameters: an integer and a lambda expression. The lambda expression represents a specific operation to be performed on the integer.

Here's a Kotlin program showcasing this concept:

Output of the above code:

In this example, the performOperation function takes an integer and a lambda expression (Int) -> Unit as parameters. The lambda expression is then invoked within the performOperation function to perform the desired operation on the given number.

Lambda Expression Which Returns Unit

A lambda expression can also return a value, typically of type Unit. For instance, let's modify the performOperation function to accept a lambda expression that returns Unit.

Here's an updated version of the previous example:

Output of the above code:

Now, the lambda expressions within the performOperation function return Unit by printing the squared and cubed values of the given number.

Lambda Expression Which Return Any of The Value Integer, string Etc

Lambda expressions can also return values of various types, such as integers or strings. Let's modify the performOperation function again, this time allowing the lambda expression to return an integer.

Here's the updated version of the previous example:

Output of the above code:

In this example, the lambda expressions return integers, representing the squared and incremented values of the given number.

Passing Function as A Parameter to Higher Order Function Kotlin

In addition to lambda expressions, Kotlin allows you to pass functions as parameters to higher-order functions.

Example:

Consider a scenario where you have a higher order function Kotlin called performCalculation that takes two integers and a function as parameters. The function represents a specific calculation to be performed between the two integers.

Here's a Kotlin program illustrating this concept:

Output of the above code:

In this example, the performCalculation function takes two integers and a function (Int, Int) -> Int as parameters. The function is then invoked within the performCalculation function to perform the specified calculation.

Kotlin Program of Passing Function Which Returns Unit

When passing a function that returns a Unit, the concept remains the same. Here's a Kotlin program demonstrating this:

Output of the above code:

In this example, the performGreeting function takes a string and a function (String) -> Unit as parameters. The function is then invoked to greet or bid farewell to the specified person.

Function Which Return Any of The Value Integer, String Etc

Passing a function that returns a value of any type follows a similar pattern. Here's a Kotlin program showcasing this concept:

Output of the above code:

Here, the performStringOperation function takes two strings and a function (String, String) -> Any as parameters, and the function is invoked to perform the desired string operation.

Returning a Function from Higher-Order Function

Kotlin's flexibility allows you to return functions from higher-order functions. Consider a scenario where you have a higher order function Kotlin called getOperation that takes an operator symbol as a parameter and returns a corresponding function. Here's a Kotlin program illustrating this concept:

Output of the above code:

In this example, the getOperation function returns a specific function based on the provided operator symbol. This allows you to dynamically obtain and use functions for different operations.

Conclusion

  • Kotlin is a statically typed programming language, which implies that variable types are determined during compile-time, not run-time.
  • Kotlin treats functions as first-class citizens, allowing functions to be passed as arguments to other functions, returned as values from functions, and stored in variables or data structures.
  • This feature of treating functions as first-class entities is essential for enabling functional programming principles.
  • Functional programming emphasizes the use of higher-order functions, and Kotlin's support for first-class functions aligns well with this practice.
  • A higher-order function Kotlin is a type of function that can accept another function as a parameter, return a function as its result, or even perform both operations. Typically, lambda expressions are used as arguments for higher-order functions or as return values from them.