There are many advanced features in Kotlin which gives an edge for the user using this language over Java. One such feature is Higher Order Functions in Kotlin.
In this Article, let us see what are the advantages of using Higher Order functions in Kotlin along with examples where and how we can use them.
Here is our YouTube video on Higher Order Functions from our channel CodeRefer. Do subscribe to receive all the latest video updates.
What you will learn by the end of this article?
By the end of this article you will be able to understand
- What is a Higher Order Function
- Advantages of a Higher Order Function
- Practical Examples of using it
Higher Order Functions
A function is called a Higher Order function if it satisfies any of the following:
- If it accepts a function as a parameter,
- If it returns a function
Advantages of Using Higher Order Functions
- Higher Order functions helps reduce the code redundancy by allowing the common code functionality to be passed as a function to another function
- Increases readability of the code.
Code Examples
You may also like:
Let us see the practical examples of Function accepting a function.
Function accepting a Function
fun main(args: Array<String>) { | |
val list = listOf(1,2,3,4,5) | |
list.forEach({a -> a*a}) | |
} |
In the above example, line 3 consists of forEach function which accepts lambda expression as a parameter. This lambda expression is being applied to each of the list item. Lambda Expressions will be explained in depth in our next article.
Function Returning a Function
Below is an example where a Function returns another function.
fun main(args: Array<String>) { | |
val areaOfSquare = area() | |
println(areaOfSquare(5)) | |
println(areaOfSquare(10)) | |
} | |
fun area() : (Int) -> Int { | |
return {i -> i * i} | |
} |
In the above snippet, at line 8, we can see that area() function returns a lambda function. which we used in our lines 3,4.
Our Next article will be on Lambda Expressions in detail and how to use them. In case of any queries, feel free to leave a comment below.
I am an Android developer and I have started learning Kotlin. Kotlin is a super form of Java. Your tutorials are helpful.
Thank you waheed.. glad you found it useful 🙂