How to pass function as parameter in Kotlin

Save

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.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

We've bought a Shopware Extension which is a hybrid App, which we can now offer in the Google Play Store and the IOS App Store. I'am still impressed how fast and how sharp the support team leads us through every process of the App-Store clarification. Very fast and useful response.

Markus Walter

Markus Walter

Founder, Das Apartment Living

Talk to Sales

Global

Live Chat
Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home