Read More

How to pass function as parameter in Kotlin

In this blog, we are going to see how kotlin lambda expression makes our code more expressive and concise. Recently, I’ve noticed that there are a few different ways to pass a function as a parameter. In this post I will use 2 functions: We have to declare the method, in such a way that it can receive the method as an argument. The most common and often more convenient (according to Kotlin documentation) is to pass a lambda expression.

1. Pass a lambda expression

In the above example, we have passed a lambda expression to calculateSum() method which will return the sum of these variables after execution of divide function. This is how we write lambda expression in a function:  Expression_Name(Param1,Param2,Param3)->RetrunType

2. Pass lambda expression directly without passing method

In this 2 example, we have lambda expression directly without passing method itself in the previous example we have passed the divide() function as the parameter. Regular functions receive only data parameters, whereas a function that receives another function as a parameter or returns a function, as a result, is called a Higher-order function. So, our functions that receive a lambda callback are basically higher-order functions.

 

Hope this blog will give you a basic idea of how we can pass lambda express or function to a method.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close