KOTLIN HIGHER ORDER FUNCTIONS
The Kotlin is a statically typed programming language developed by JetBrains. And know KOTLIN is the official language of Android announced by Google I/O.
What are functions?
Kotlin functions are stored in data variables and data structure, it can also pass as an argument to higher order functions.
There are two types of functions available in kotlin are
- Kotlin Standard Library Functions Kotlin Standard Library Function is build-in functions available at any time while it is needed.
- User-defined functions User-defined functions are the functions defined by the user to perform certain tasks.We can create our functions ourselves.
How to use functions
Functions can perform the task defined by the user as per the call to function at the time that we needed this is done by only creating a function with fun keyword followed by the function_name given by the user itself and calling the function by function_name () format.
Single Expression Functions
We can avoid the return type and the curly braces if the function while it returns a single expression.
Unit returning Functions
Functions which do not return any value like void in Java called Unit.
What is the Higher order function?
In Kotlin ,a function can accept function as a parameter and also can return a function is called Higher order functions.
Passing lambda expression as a parameter for higher order function
A Lambda function is a function which does not have a function name. It can be passed as an argument to the higher order function to reduce the task complexity.
We can pass lambda functions to higher order function by two ways
- Passing Lambda returns Unit
- Passing Lambda returns values
Lambda expression with unit is represented by the empty parenthesis () which does not contain any values passed to it. On the other hand lambda expression having argmented parentheses’ (value 1, value2…) returns some values to the higher order as well as to the lambda expression.
Other than Lambda functions we can also pass functions as a parameter to Higher order function. This is also done in two ways like in lambda expression such that
- Passing functions returns Unit
- Passing functions returns values
While passing functions into Higher order function, we need to specify the type and parameters of values inside the functions.
Advantages of using Higher Order Functions
- Higher order functions helps to reduce the code redundancy
- Increase readability of the code