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:-
1 2 3 4 5 6 7 8 |
fun main(args: Array<String>) { var a = 5 println(someMethod(a, {println("W3Adda: Kotlin Inline Functions")})) } fun someMethod(a: Int, func: () -> Unit):Int { func() return 5*a } |
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.
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:-
1 2 3 4 5 6 7 8 |
fun main(args: Array<String>) { var a = 5 println(someMethod(a, {println("W3Adda: Kotlin Inline Functions")})) } inline fun someMethod(a: Int, func: () -> Unit):Int { func() return 5*a } |
Bytecode:- Let’s look at the bytecode of the above code by going to Tools-> Kotlin-> Show Bytecode.