Signup/Sign In

Kotlin Inline Keyword

In this tutorial we will discuss about Inline function in Kotlin using the inline keyword. Inline functions help us to save memory at runtime and hence increase the performance of our application.

In previous tutorials we discussed about lambda expressions and higher order functions. Let us take the same example:

fun higherOrderFunction(functionName: (name: String)->Unit, name: String){
    println("In higher order function")
    println("Calling received function...")
    functionName(name)
}
fun main() {
    higherOrderFunction({ name: String ->
        println("Inside the lambda function")
        println("Say hello to $name")
    }, "Ninja")
}

In IntelliJ, we can generate the bytecode of our Kotlin program. For that go to Tools > Kotlin > Show Kotlin Bytecode. We can decompile this bytecode and generate the equivalent Java code.

We will observe that for the lambda expression a new Function object is created. But this is not what we wanted.

Each higher order function will create a new object and allocate memory to it. It will increase runtime overhead. To overcome this problem, we use inline functions.

Kotlin Inline Function

To avoid creation of new object for each higher order function, we can use inline keyword. It will help us increase the performance of the code. The inline keyword, instead of creating the new object for higher order function, copies the code inside inline function to the place from where it is called.

The inline keyword is added before the function.

inline fun higherOrderFunction(functionName: (name: String)->Unit, name: String){
    println("In higher order function")
    println("Calling received function...")
    functionName(name)
}

fun main() {
    higherOrderFunction({ name: String ->
        println("Inside lambda function")
        println("Say hello to $name")
    }, "Ninja")
}

If we add inline keyword before a normal function, it will not lead to any performance change. Even Intellij will suggest to remove it.

Keep in mind that inline keyword should only be used when the higher order function is short. If higher order function contains a lot of code then the generated code will be really lengthy.

Summary

In this tutorial we discussed about Inline functions. They are a bit difficult to understand at first. The only point of adding inline keyword is to enhance the performance.



About the author:
I'm a writer at studytonight.com.