5

Diving into Higher order functions and lambdas in Kotlin

 3 years ago
source link: https://sourcediving.com/diving-into-higher-order-functions-and-lambdas-in-kotlin-e07656cdffe1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Diving into Higher order functions and lambdas in Kotlin

Image for post
Image for post
Photo by Teddy Kelley on Unsplash

When I joined Cookpad few months back, I was a little muddled when first looking at the code, and no wonder why, as the codebase extensively uses Lambdas and Higher order functions and these were new to me. I had to take some time to explore and here are some findings that might come in handy for you too.

1. Lambdas

Let’s dive into definitions of Lambda expressions: Lambda expressions and anonymous functions are ‘function literals’, i.e. functions that are not declared, but passed immediately as an expression. By “expression” we mean we can pass as arguments to functions or return as a function. Let’s discuss this with example to understand more clearly:

val multiply : (Int, Int) -> Int = { x, y -> x * y }

In the above code, the variable multiplywill be stored as a function in memory when executed. And if we look at the code at a leisurely pace:

1. (Int, Int) acts as arguments and
2. Int after right arrow( →) acts as return type.
3. And if you look at on the other side after equals(=), we can write any logic inside { } which is a functionto return Integer value from our logic.

We can also write above function like this:

val multiply = { x:Int, y:Int -> x * y }

Where kotlin type inference will know the return type, which is Int. So considering our example, we can simply call multiply function with two Integer arguments:

val result = multiply(3 , 6) //returns 18

I hope lambdas are bit clearer now, moving on to:

2. Higher order functions with lambdas

As per the definition from wikipedia: A higher order function is a function that takes functions as parameters, or returns a function. Let’s discuss this with an example and main structure like below:

class MainClass {               fun function1(function2 : () → Unit) {                   function2() //Executes function2 here               }}

Let’s split this function into different parts to understand it better:

1. function2 is name of the function
2. () represents that function2 takes no arguments
3. Unit represents function2 does not return anything.

If we combine altogether:
i. function1 is a function which takes function2 as an argument
ii. function2 is a function which takes zero parameters and does not return anything

You might be confused by reading word “function” over and again but I recommend you to read at leisurely pace to understand it clearly.

Now it’s time to understand these functions with example in Android:

fun Group.setAllOnClickListener(listener: () -> Unit) {    referencedIds.forEach { id ->rootView.findViewById<View>(id).setOnClickListener {              listener() // listener() function executes here        }
}
}

Again, let’s split this function into different parts to understand it better:

1. Group is widget from constraintLayout
2. setAllOnClickListener is extension function which takes listener: () -> Unit asargumentwhich does not return anything.

class ExampleViewHolder {

fun bind(user: User, onUserGroup: (userId: String) -> Unit) {

openUserDetails.setAllOnClickListener {
onUserGroup(user.id)
}

}
}

In above code :

1. ExampleViewHolder is a view holder class in recycler view
2. bind is a function to bind item in recycler which takes onUserGroup: (userId: String) -> Unit as argument3. openUserDetails is a group view which is holding layout references inside ConstraintLayout

The above code is small example to understand how we can use Higher order functions seamlessly in Android. There are many other ways how you can take advantage of Higher order functions in Kotlin, but for this small post I would like to keep it simple with above example.

Yayy!! that’s the end of this 3 min read post, I hope you have learnt something interesting. If you like it give thumbs up and share with your Kotlin buddies.

At Cookpad our Android codebase is entirely cooked with Kotlin and we always thrive to utilise Kotlins best features. Thanks to all my teammates for such nice job :).


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK