Android Kotlin just got easier with Higher Order Function

Tram Ho

Introduce

Articles with the topic Higher Order Functions for those new to Kotlin.

If you are an Android developer coming from Java, I will definitely comment that Kotlin is really “cool”. One of the things that makes this magic is the functional programming support. That is, functions can be passed as a variable of another function, and can also be returned from a certain function. That is the Higher Order Function.

Definition of a Higher Order Function

Let’s take a look at the following basic example

Of the three parameters passed to the rollDice function, the third parameter is a function

In there, the callback is the name of the functions, and the name of the parameter passed. (result: Int) again the parameter of the callback . Unit is the return type of the function. In this case, it doesn’t need to return anything.

Next we call the Higher Order Function.

Here, result is the parameter of the callback function. The println command is the work done corresponding to the above callback function.

See practical example

Here we come to a few lines of code offline.

Where you want to show Dialog.

Add another example, also ExampleDialog above but with 2 callbacks.

And here is the function call Dialog:

Hope the above examples will give you more practical insight about Higher Order Function. Not only are they useful, but they’re also cool, aren’t they !!!

Share the news now

Source : Viblo