Kotlin: Inline function

Sagar Patel
3 min readMay 4, 2020

Prerequisite:

  1. Kotlin: Function type, higher order function, function literal, lambda expression and an anonymous function
  2. Kotlin: Extension function and Receiver type

We know that a new function object is created for each and every function type in a higher-order function. It causes memory allocation and hence, runtime overhead. To avoid this or say, to improve the performance, we can use the keyword inline.

However, that doesn’t mean we should inline each and every function! In fact, when we try to inline a function that is not accepting a function type, the IDE will tell us to remove the inline keyword.

Also, we should not inline any higher-order function that has more than 3 lines because generated code grows a lot for an inline function. You can check the Kotlin standard library to get an idea about when to use inline functions.

When using an inline function, we are not allowed to pass a function type parameter to another function. However, if it is necessary, we can mark such a function type as a noinline.

Ok, enough theory!

Let us understand it by an example:

Suppose we have our higher-order function like below:

So, in such case, in order to prevent new function object creation, we can make the function inline as below:

However, if we are passing any function type to another function like below:

Here, the compiler will complain to us: Illegal usage of inline function type ftOne…

To solve that, we can rewrite our function as below:

However, if there is only one lambda parameter and we are passing it to another function, it doesn’t make any sense to make such a higher-order function inline and the compiler will also suggest the same!

Let us understand it by an example:

Suppose we have a higher-order function like below:

Here, the compiler will tell us to not use the inline keyword when there is only one lambda parameter and we are passing it to another function. So, we can rewrite the above function as below:

Note that we had to remove the keyword noinline as well because it can be used only for inline functions!

That’s all!

If you have read this article, if this article has helped you, you can click and hold on that 👏icon for a few seconds 😉. Your 👏 motivates me to write more articles. 😇

Previous article: Kotlin: Extension function

Where to go from here? What to learn next?: Kotlin: Scope function

You can follow me here on medium or on various social networks to get the notification when I publish a new article or to discuss on android development, soft skill development or on various ideas and hacks. Let us become better together.

Let us learn together from each other’s experience.

Let us be Connected

Tags: kotlin, inline function

Originally published at https://dev.to on May 4, 2020.

--

--