Higher-Order Functions:
Functions that return a function as their result, and function types which enable you to define functions as values. Some programming languages are purely functional, meaning the entire application is structured in this
style.
While Kotlin is not a pure functional programming language, it does provide many functional tools to allow developers to express logic in a functional paradigm. Here, we write our code-part after ->
sign where type annotation is optional.
We must explicitly declare the type of our lambda expression. If lambda returns no value then we can use Unit
pattern : (Input) -> Output
But to understand Higher-Order functions with examples we need to learn about lambda expressions.
Lambda Expression:
A lambda expression is always surrounded by curly braces {}
and arguments are declared inside the curly braces.
Syntax of lambda functions:
val lambda_name : Data_type = { variable -> body_of_function }
It will be easy to understand with an example:
We can use lambda functions to simply add to numbers 'a' and 'b'.
example with type annotation:
val add = { a: Int, b: Int ->
val num = a + b
}
example without type annotation:
val add:(Int,Int)-> Int = { a , b ->
val num = a + b
}
Adding two numbers using lambda-functions:
val add = { a: Int, b: Int ->
val num = a + b
num.toString() //convert Integer to String
}
fun main() {
val result = add(2,3)
println("The sum of two numbers is: $result")
}
Output:
The sum of two numbers is: 5
We can pass a lambda expression as a parameter to Higher-Order Function. Now we will go through Higher-Order functions:
var greeting = {println("Hello, My name is Amandeep Singh") }
// using higher-order function
fun higherfunction( greet: () -> Unit ) { // use of lambda as a parameter
greet() //invokes lambda function
}
fun main() {
//call higher-order function
higherfunction(greeting) // passing lambda as parameter
}
Output:
Hello, My name is Amandeep Singh
That's it for lambda and Higher-Order functions. Now you have a tight grip over them.
If you have any doubt or suggestion you can share it in the discussion section.
Wanna connect? connect with me on LinkedIn
Top comments (0)