Skip to content

Higher order functions

Devrath edited this page Feb 11, 2024 · 15 revisions

Definition

  • Higher-order functions are the ones that take functions as parameters or return function as a result.
  • We can even store the higher-order function in a variable and a data structure.
  • They enable functional programming concepts and allow you to write more concise and expressive code.

Declaring Functions

  • Functions in kotlin have a type
  • The same way as we can declare Int,String,Person we can declare something of type function
  • A type is composed of FunctionParameters + FunctionReturnType
  • (Parameters are declared within these brackets) --> ReturnType

Examples of declaring functions

A function that takes a single parameter Int and returns a Unit(A unit means nothing like void)

(Int) -> Unit

A function that takes two parameters Int and String and returns Unit

(Int,String) -> Unit

A function that takes String as a parameter and returns Int

(String) -> Int

Passing Functions

  • We can pass functions to other functions and return functions from others.
  • How we do this
    • Declare a function as having another function as a parameter.
    • When using the first function, We pass the second function as an argument.

More reading

Clone this wiki locally