Kotlin inline functions

In this tutorial you will learn about the Kotlin inline functions and its application with practical example.

Kotlin inline functions

In Kotlin, high order functions allows you to pass functions as parameters as well as return functions. But these functions are stored as objects and have there own callbacks attached with subsequent memory allocations. The memory allocation for function objects and classes and virtual calls introduces run-time memory overhead.

Let’s check out a high order function code snippet below, and understand how these functions are passed as parameters internally and how they works internally .

Example 1:-

Here, someMethod is called with println as the parameter, this lambda expression (println) will further create an additional function call which results in further dynamic memory allocation.

Bytecode:- Let’s look at the bytecode of the above code by going to Tools-> Kotlin-> Show Bytecode.

kotlin inline function 1

Here, you would notice a chained method calls. This way if we call multiple functions as parameters each of them would further add up the method count thus it will introduces significant memory and performance overhead.

This memory overhead issue can be avoided by declaring the function inline. The inline annotation copies the function as well as function parameters in run-time at call site that reduces call overhead. An inline function tells the compiler to copy these functions and parameters to call site. A function can declared as inline by just adding inline keyword to the function as following –

Example 2:-

Bytecode:- Let’s look at the bytecode of the above code by going to Tools-> Kotlin-> Show Bytecode.


kotlin inline function 2

noinline

Inline Properties

Non-local returns

Reified type parameters

In this tutorial we have learn about the Kotlin inline functions and its application with practical example. I hope you will like this tutorial.