Inline functions

While functions are a great way to write modular code, it may sometimes increase program execution time and reduce memory optimization due to function stack maintenance and overhead. Inline functions are a great way to avoid those hurdles in functional programming. For example, see the following code snippet:

    fun doSomeStuff(a:Int = 0) = a+(a*a) 
 
    fun main(args: Array<String>) { 
      for (i in 1..10) { 
        println("$i Output ${doSomeStuff(i)}") 
      } 
    } 

Let's recite the definition of inline function; it says that inline functions are an enhancement feature to improve the performance and memory optimization of a program. Functions can be instructed to the compiler to make them inline so that the compiler can replace those function definitions wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime; thus, no extra memory is needed for a function call, stack maintenance, and more, and getting the benefits of functions as well.

The preceding program declares a function that adds two numbers and returns the result, and we will call the function in the loop. Instead of declaring a function for this, we can write the addition code right in the place where we will call the function, but declaring a function gives us freedom to modify the addition logic anytime without any effect on the remaining code, for example, if we want to modify the addition with multiplication or something else. If we declare a function as inline, then the code inside that function will replace all the function calls, thus improving performance while keeping our freedom intact. Consider the following code snippet as an example:

    inline fun doSomeStuff(a:Int = 0) = a+(a*a) 
 
    fun main(args: Array<String>) { 
      for (i in 1..10) { 
        println("$i Output ${doSomeStuff(i)}") 
      } 
    } 

Here is the output of the program:

There is one more feature Kotlin provides with inline functions–if you declare a high-order function as inline, then the inline keyword affects both the function itself and the lambda passed to it. Let's modify the high-order function code with inline:

    inline fun highOrderFuncInline(a:Int, validityCheckFunc:(a:Int)- 
>Boolean) { if(validityCheckFunc(a)) { println("a $a is Valid") } else { println("a $a is Invalid") } } fun main(args: Array<String>) { highOrderFuncInline(12,{ a:Int -> a.isEven()}) highOrderFuncInline(19,{ a:Int -> a.isEven()}) }

The compiler will replace all calls to validityCheckFunc with its lambda, as it would do with highOrderFuncInline with its definition. As you can see, there's not much modification of the code, just a small change of adding inline before a function declaration can improve performance.