Inline Function

An inline function is declare with a keyword inline. The use of inline function enhances the performance of higher order function. The inline function tells the compiler to copy parameters and functions to the call site.

The virtual function or local function cannot be declared as inline. Following are some expressions and declarations which are not supported anywhere inside the inline functions:

  • Declaration of local classes
  • Declaration of inner nested classes
  • Function expressions
  • Declarations of local function
  • Default value for optional parameters

Let's see the basic example of inline function:

Output:

calling inline functions
code inside inline function

Non local control flow

From inline function, we can return from lambda expression itself. This will also lead to exit from the function in which inline function was called. The function literal is allowed to have non local return statements in such case.

Output:

calling inline functions

crossinline annotation

To prevent return from lambda expression and inline function itself, we can mark the lambda expression as crossinline. This will throw a compiler error if it found a return statement inside that lambda expression.

noinline modifier

In inline function, when we want some of lambdas passed in inline function to be an inlined, mark other function parameter with noinline modifier. This is used to set expressions not to be inlined in the call.

Output:

calling inline functions
next parameter in inline functions
code inside inline function
this is main function closing

If an inline function does not contain any noinline function parameter and no reified type parameters then compiler will generate a warning.


Next TopicKotlin Array




Latest Courses