Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Inline Functions and reified

Kotlin Inline Functions and reified

Lambdas are lightweight to use, but on the JVM every lambda is compiled into a function object, and frequent calls to these objects incur real overhead.

inline makes the compiler copy the function body and the lambda body directly to the call site, eliminating the function object and call overhead; it is also the prerequisite for reified type parameters to exist.

This chapter explains why inlining is needed, the difference between noinline and crossinline, the rules of non-local returns, and when inline should not be used.


Why inlining is needed

Without inline, a function that takes a lambda works like this after compilation: the caller first creates a function object, passes it to the function, and the function calls it via invoke().

If such a function is called thousands of times in a loop, thousands of temporary objects are created.

Example

// File path: InlineBasic.kt

// Ordinary higher-order function: the lambda is compiled into a function object

fun runTask

(

action

:

(

)

->

Unit

)

{

    action

(

)

}

// Inline function: the compiler copies the function body and lambda body to the call site

inline fun runTaskInline

(

action

:

(

)

->

Unit

)

{

    action

(

)

}

fun main

(

)

{

    runTask

{

println

(

"Normal call: RUNOOB"

)

}

    runTaskInline

{

println

(

"Inline call: RUNOOB"

)

}

}

The two produce exactly the same output; the difference lies only in the compiled result.



普通调用:RUNOOB

内联调用:RUNOOB

You can inspect the bytecode with javap -p -c InlineBasicKt: a normal call creates a function object and calls its invoke, while an inline call leaves only two println instructions.

Comparison Item Ordinary higher-order function Inline functions
Lambda parameter Compiled into a function object Expanded directly at the call site, no object created
How to call Called via invoke Code inlined, no extra call
Generated code size Smaller; only one copy of the function body A copy at every call site, so the size grows
Non-local returns Not supported Supported

The inline keyword

Adding inline before fun makes an inline function; its function body and all function-type parameters are expanded at the call site.

Inline function compile-time expansion comparison: the call site calls inline fun log, at compile time the function body is moved into the call site, expanding to main() { println("hi") }, no extra function object is generated; the dashed note at the bottom explains that the non-inline version generates a function object for the lambda

Ordinary value parameters (non-function types) are simply copied over, while function-type parameters are copied together with their lambda bodies.

Example

// Add an inline forEach-style extension to List

inline fun

<

T

List

<

T

.

forEachRunoob

(

action

:

(

T

)

->

Unit

)

{

   

for

(

element in

this

)

{

        action

(

element

)

     

// After inlining, this expands directly into the lambda's code

   

}

}

fun main

(

)

{

    val sites

=

listOf

(

"Runoob"

,

"www.runoob.com"

,

"RUNOOB"

)

    sites.

forEachRunoob

{

        println

(

it

)

   

}

}



Runoob

www.runoob.com

RUNOOB

The call syntax of an inline function is exactly the same as a normal function; the caller does not need to know it is inlined.

The standard library's forEach, map, filter, let, run, apply, also, and repeat are all inline functions, which is why they can support non-local returns.


Non-local returns

The most obvious benefit of inline functions is that a return inside the lambda can return directly from the outer function, which is called a non-local return.

Because the lambda's code has been copied into the caller's function, after compilation this return sits inside the outer function's body.

Example

inline fun

<

T

List

<

T

.

forEachRunoob

(

action

:

(

T

)

->

Unit

)

{

   

for

(

element in

this

)

{

        action

(

element

)

   

}

}

fun main

(

)

{

    listOf

(

1

,

2

,

3

,

4

,

5

)

.

forEachRunoob

{

       

if

(

it

==

3

)

return

         

// Non-local return: return directly from main

        println

(

it

)

   

}

    println

(

"This line will not execute"

)

}



1

2

Remove the inline above and the code will not compile, because a normal function's lambda is a separate object and cannot jump back to the caller.

Example

// Non-inline function: the following will fail to compile

fun runTask

(

action

:

(

)

->

Unit

)

{

    action

(

)

}

fun main

(

)

{

    runTask

{

       

// Compilation error: 'return' is not allowed here

       

// return

        println

(

"Can only return normally, cannot jump out of main"

)

   

}

}

Note:Non-local returns only work when the lambda is passed directly as an argument to an inline function. If the lambda is first stored in a variable or passed to a normal function, it loses the inline context and can no longer jump out of the outer function.


noinline

A function-type parameter of an inline function is inlined by default; if a lambda needs to be stored in a variable or passed as an argument to another function, use noinline to disable its inlining.

A parameter marked noinline still creates a function object, so only add it when you truly need to use the lambda as a value.

Example

// onFinish is used as a value, so mark it noinline; action stays inlined

inline fun runTask

(

noinline onFinish

:

(

)

->

Unit, action

:

(

)

->

Unit

)

{

    action

(

)

   

// A noinline lambda can be assigned to a variable or passed to other functions

    val handler

:

(

)

->

Unit

=

onFinish

    handler

(

)

}

fun main

(

)

{

    runTask

(

        onFinish

=

{

println

(

"Task finished: RUNOOB"

)

}

,

        action

=

{

println

(

"Task running: www.runoob.com"

)

}

   

)

}



任务执行:www.runoob.com

任务结束:RUNOOB

If you remove noinline, the compiler reports an error saying an inline parameter cannot be stored, because it is no longer a real object.


crossinline

Another case: the lambda is still inlined, but it is placed in another execution context, such as inside another lambda or an object expression.

In that case, use crossinline, which keeps inlining while forbidding non-local returns inside that lambda.

Example

// crossinline: block remains inlined, but non-local returns are not allowed

inline fun runCrossInline

(

crossinline block

:

(

)

->

Unit

)

{

   

// block is placed in a Runnable's lambda, which is another execution context

    val task

=

Runnable

{

block

(

)

}

    task.

run

(

)

}

fun main

(

)

{

    runCrossInline

{

        println

(

"Code in crossinline: RUNOOB"

)

       

// Compilation error: 'return' is not allowed here

       

// return

   

}

}



crossinline 中的代码:RUNOOB

Without crossinline, placing block inside Runnable as above reports an error, indicating that the parameter needs a crossinline modifier.

The standard library's sortedBy uses crossinline because it passes the selector to compareBy, which is use in another context.

Modifiers Inlined or not Non-local return allowed Typical scenario
Default Is You can Lambda called directly inside the function body
noinline No No Lambda must be stored in a variable or passed to other functions
crossinline Is No Lambda called inside another lambda or an object

reified type parameters

JVM generics are erased after compilation, so the concrete type argument is unavailable at runtime, and you cannot write is T or T::class in an ordinary generic function.

reified preserves the type argument at the call site, and the compiler replaces T with the real type, thereby bypassing type erasure.

It can only be used on inline functions, because only inlining lets the concrete type be seen at each call site.

Example

// reified must be used together with inline

inline fun

<

reified T

Any

?

.

isInstanceOf

(

)

:

Boolean

=

this

is T

// Get the type name at runtime

inline fun

<

reified T

typeName

(

)

:

String

=

T

::

class

.

simpleName

?:

"Unknown type"

class

Site

(

val name

:

String

)

fun main

(

)

{

    val value

:

Any

=

"RUNOOB"

    println

(

value.

isInstanceOf

<

String

(

)

)

println

(

value.

isInstanceOf

<

Int

(

)

)

println

(

typeName

<

String

(

)

)

println

(

typeName

<

Int

(

)

)

println

(

typeName

<

Site

(

)

)

}


true

false

String

Int

Site

The most practical use of reified is type filtering together with collections, which is how the standard library's filterIsInstance is implemented.

Example

inline fun

<

reified T

List

<*>

.

filterIsInstanceRunoob

(

)

:

List

<

T

{

    val result

=

mutableListOf

<

T

(

)

for

(

element in

this

)

{

       

if

(

element is T

)

{

     

// Thanks to reified, we can check the type of T here

            result.

add

(

element

)

       

}

   

}

   

return

result

}

fun main

(

)

{

    val mixed

:

List

<

Any

=

listOf

(

1

,

"Runoob"

,

2

,

"RUNOOB"

,

3.14

)

    val strings

=

mixed.

filterIsInstanceRunoob

<

String

(

)

println

(

strings

)

}


[Runoob, RUNOOB]

Note:reified can only perform type checks and obtain type information; you cannot directly write T() to create an instance, because the compiler does not know what T's constructor looks like. When you need to create an instance, you can accept an extra constructor-reference parameter.


@PublishedApi

A public inline function is copied into the caller's module, so if it accesses internal or private declarations internally, the bytecode of those declarations must also be visible to the caller.

@PublishedApi marks such declarations, making the compiler generate public bytecode for them while still keeping internal visibility at the Kotlin level.

Example

class

SiteValidator

{

   

// An internal member called by a public inline function needs @PublishedApi

    @PublishedApi

    internal fun checkName

(

name

:

String

)

:

Boolean

=

name.

isNotEmpty

(

)

    inline fun validate

(

name

:

String

)

:

Boolean

=

checkName

(

name

)

}

fun main

(

)

{

    val validator

=

SiteValidator

(

)

    println

(

validator.

validate

(

"Runoob"

)

)

    println

(

validator.

validate

(

""

)

)

}



true

false

Remove @PublishedApi and the compiler reports an error saying a public inline function cannot access a non-public API.


When not to use inline

inline is not a "faster switch"; it essentially trades code size for runtime overhead.

The larger the function body and the more call sites, the more noticeable the size inflation from copying, which may even slow things down due to instruction-cache misses.

Good uses of inline Poor uses of inline
Small function body that takes a lambda parameter Long function body with complex logic
Need for reified type parameters No function-type parameters and no need for reified
Need for non-local returns to simplify control flow Lambda needs to be stored or passed on (use noinline instead)
High call frequency, wanting to avoid lambda object allocation Very many call sites combined with a large body, causing size to grow sharply

A simple rule of thumb: only consider adding inline when the function "takes a lambda parameter" or "needs reified"; in other cases it is usually not worth it.


Common questions

Below are a few common questions about inline functions.

Problem Description
Does inline always make a program faster Not necessarily; it saves lambda object and call overhead but increases code size, which may slow things down when the body is large
Why does my return fail to compile Non-local returns require the lambda to be passed directly to the inline function; if it is stored in a variable, this no longer holds
What is the difference between noinline and crossinline noinline is not inlined and can be used as a value; crossinline is still inlined but forbids non-local returns
Can reified be used on a normal function No; reified is only allowed on type parameters of inline functions
Why does accessing internal from an inline function report an error An inline function is copied into other modules, so the accessed declaration needs @PublishedApi