Skip to content

LanguageIdiomaภาษา

Understanding inline, crossinline, noinline, reified, and where Keywords in Kotlin

Understanding inline, crossinline, noinline, reified, and where Keywords in KotlinEntender las palabras clave inline, crossinline, noinline, reified y where en Kotlinทำความเข้าใจคีย์เวิร์ด inline, crossinline, noinline, reified และ where ใน Kotlin

AndroidAndroidAndroid

ByPorโดย David Cruz Anaya, Mobile & Applied AI EngineerIngeniero sénior de móvil e IA aplicada (Android, Kotlin Multiplatform, IA de producto)วิศวกรมือถือและ AI ประยุกต์ระดับอาวุโส (Android, Kotlin Multiplatform, AI ของผลิตภัณฑ์)

9 min read9 min de lecturaอ่าน 9 นาที
KotlinAndroidInline FunctionsGenericsPerformanceMobile Development
Share:Compartir:แชร์:

Kotlin keywords inline, crossinline, noinline, reified, and where on a deep-dive cover

The Problem These Keywords Solve

Kotlin makes higher-order functions and generics feel effortless. You pass lambdas around like values and write generic code without much ceremony. That convenience hides a cost. Every lambda you pass is, by default, an object the runtime has to allocate. Every generic type parameter is erased at compile time, so the type you wrote disappears before the program runs.

inline, noinline, and crossinline decide how lambdas get compiled. reified keeps a generic type that the JVM would otherwise erase. where lets a single type parameter satisfy several constraints at once.

What Does inline Do?

The inline modifier tells the compiler to copy the function’s body, and the bodies of any lambdas you pass to it, directly into the call site. There is no function call and no lambda object at runtime. The bytecode reads as if you wrote the logic inline by hand.

Heads up: inline is overloaded. This post covers inline functions. Kotlin reuses the word for two other features. Inline (value) classes wrap a single value with no runtime allocation (@JvmInline value class UserId(val raw: String)), and inline properties inline their accessor code. Same keyword, different mechanics. Everything below is about functions.

Without inline, a function that takes a lambda allocates a Function object every time you call it. In a hot loop or a frequently called helper, those allocations add up. The official docs are blunt about the cost: each function is an object that captures a closure, and “memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead” (Kotlin docs, Inline functions).

inline fun measure(block: () -> Unit) {
    val start = System.nanoTime()
    block()
    println("Took ${System.nanoTime() - start} ns")
}

fun main() {
    measure {
        // This lambda body is copied into main().
        // No Function0 object is allocated.
        (1..1_000).sum()
    }
}

Inlining also enables non-local returns. Because the lambda body is pasted into the caller, a plain return inside the lambda returns from the enclosing function, not just the lambda. That is exactly why forEach from the standard library can do this:

fun findFirstEven(numbers: List<Int>): Int? {
    numbers.forEach {
        if (it % 2 == 0) return it // returns from findFirstEven, not just the lambda
    }
    return null
}

A word of caution from experience: inline is not free. Copying a large function body into many call sites bloats your bytecode. The Kotlin team gives the same warning, noting that inlining “may cause the generated code to grow” and advising you to avoid inlining large functions (Kotlin docs, Inline functions). Reserve it for small functions that take lambdas. Inlining a big function with no lambda parameters usually does more harm than good, and the compiler will warn you about it.

When Should You Use noinline?

Once a function is marked inline, all of its lambda parameters are inlined by default. Sometimes that is a problem. An inlined lambda has no object representation, so you cannot store it in a variable, put it in a collection, or pass it to a function that expects a real lambda object. The noinline modifier opts a single parameter out of inlining. As the docs put it, “noinline lambdas… can be manipulated in any way you like, including being stored in fields or passed around” (Kotlin docs, Inline functions).

inline fun runTasks(
    immediate: () -> Unit,
    noinline deferred: () -> Unit
) {
    immediate()                 // inlined, no allocation
    pendingCallbacks.add(deferred) // needs a real object reference, so noinline
}

val pendingCallbacks = mutableListOf<() -> Unit>()

Here immediate stays inlined for performance, while deferred becomes an ordinary lambda object you can stash in a list and invoke later. If you tried to add immediate to the list, the compiler would reject it because there is no object to add.

Use noinline when one lambda needs to outlive the function call or travel somewhere the inlined version cannot go.

What Problem Does crossinline Solve?

crossinline keeps a lambda inlined but bans non-local returns from it. You need this when the lambda is not called directly by the inline function, but instead runs inside another execution context, such as a nested lambda, an anonymous object, or a Runnable. The docs describe exactly this case: when an inline function calls a lambda “not directly from the function body, but from another execution context, such as a local object or a nested function,” non-local control flow is no longer allowed (Kotlin docs, Inline functions).

A non-local return only makes sense when the lambda body executes in the caller’s frame. The moment you hand the lambda to a separate object that runs later, returning from the outer function is impossible. The compiler forces you to acknowledge that with crossinline.

inline fun runOnThread(crossinline block: () -> Unit) {
    val task = Runnable {
        block() // called from inside the Runnable, a different context
    }
    Thread(task).start()
}

Without crossinline, this does not compile. The compiler refuses to inline block inside the Runnable because a non-local return there would have nowhere to return to. Marking the parameter crossinline says “inline it, but I promise not to return non-locally,” and the code compiles.

If you call the lambda directly, plain inline is enough. If you wrap it in another object or lambda, you need crossinline. If you need to store or forward it, you need noinline. A single lambda cannot be both noinline and crossinline, since they pull in opposite directions. Both modifiers are also exclusive to inline functions: noinline and crossinline only mean something on a lambda parameter of an inline function, and the compiler rejects them anywhere else.

How Does reified Beat Type Erasure?

On the JVM, generic type arguments are erased at compile time. The Kotlin docs state that “there is no general way to check whether an instance of a generic type was created with certain type arguments at runtime,” so the compiler prohibits checks like list is T (Kotlin docs, Generics: type erasure). The usual workaround is to pass a Class<T> parameter by hand, which is noisy.

reified removes that noise, but it only works inside inline functions. Because the function is inlined, the concrete type is known at every call site, so the compiler can substitute the real type wherever you reference T.

inline fun <reified T> Any.isInstanceOf(): Boolean = this is T

inline fun <reified T> parseJson(json: String): T =
    Gson().fromJson(json, T::class.java)

// Call site: no need to pass User::class anymore.
val user: User = parseJson(jsonString)

Compare it to the non-reified version, where you would write fun <T> parseJson(json: String, clazz: Class<T>) and pass User::class.java at every call. reified lets the call site stay clean while the type information survives into the function body. The docs confirm that “normal functions (not marked as inline) cannot have reified type parameters” (Kotlin docs, Reified type parameters). Drop the inline, and reified stops compiling.

reified hands you is T, as T, and T::class, but not a constructor. You cannot write T() to instantiate the type, and you cannot reach T’s companion object or static members. When you need those, pass a factory lambda or a KClass<T> argument explicitly. You will hit this exact pattern in larger projects, such as the generic repositories in the Kotlin Multiplatform clean architecture blueprint.

What Is the where Keyword For?

where is the odd one out here. It has nothing to do with inlining or lambdas. It declares multiple upper bounds on a generic type parameter. Kotlin lets you write a single bound inline, as in <T : Comparable<T>>, but the moment a type parameter needs two or more bounds, you must move them to a where clause. The rule is explicit in the docs: “only one upper bound can be specified inside the angle brackets. If the same type parameter needs more than one upper bound, you need a separate where-clause” (Kotlin docs, Generics: upper bounds).

Before the constraint, recall how a generic function is declared: the type parameter sits before the function name, and you either pass it explicitly or let the compiler infer it (Kotlin docs, Generic functions).

// The type parameter <T> goes before the function name.
fun <T> singletonList(item: T): List<T> = listOf(item)

val a = singletonList<Int>(1) // explicit type argument
val b = singletonList(1)      // inferred, same result

A single upper bound goes right after the type parameter, inside the angle brackets:

// T is restricted to types that are Comparable with themselves.
fun <T : Comparable<T>> greater(a: T, b: T): T = if (a > b) a else b

That is the limit: one bound in the brackets. The moment a type parameter needs two or more bounds, you move them into a where clause.

// T must be BOTH Comparable<T> and CharSequence at the same time.
fun <T> printSortedLengths(items: List<T>)
    where T : Comparable<T>, T : CharSequence {
    items.sorted().forEach { item -> println(item.length) }
}

Here T must be Comparable<T> so the list can be sorted, and CharSequence so each item exposes .length. Neither bound alone is enough; the where clause expresses the intersection.

where even combines with the keywords above. A reified inline function can carry a where clause when its type argument also needs bounds:

// reified lets us filter by T at runtime; where bounds T to Comparable.
inline fun <reified T> smallestOfType(items: List<Any>): T?
    where T : Comparable<T> {
    return items.filterIsInstance<T>().minOrNull()
}

val mixed: List<Any> = listOf("skip", 3, 1, 2, "x")
println(smallestOfType<Int>(mixed)) // 1

That single declaration pulls together three of the five keywords: inline makes it inlinable, reified keeps T available for filterIsInstance, and where constrains T so minOrNull can compare elements.

Quick Comparison

Keyword Applies to What it does Requires inline?
inline function Copies body and lambdas to the call site; removes lambda allocation; enables non-local returns n/a
noinline lambda parameter Opts one lambda out of inlining so it can be stored or passed onward Yes
crossinline lambda parameter Keeps the lambda inlined but forbids non-local returns Yes
reified type parameter Makes a generic type available at runtime, defeating type erasure Yes
where type parameter Declares multiple upper bounds on a generic No

When to Use Each: A Decision Guide

Reach for inline when you write a small higher-order function that runs often and you want to remove lambda allocation overhead, or when you need non-local returns. Skip it for large functions without lambda parameters.

Add noinline to a specific parameter the moment you need to store that lambda, add it to a collection, or pass it to a non-inline function. Add crossinline instead when the lambda is invoked from a nested context like a Runnable or anonymous object and you want to keep it inlined.

Reach for reified whenever you find yourself passing a Class<T> argument purely to work around type erasure, and you are willing to make the function inline. And where only earns its place when one type parameter needs more than one upper bound.

Marking a function inline because it sounds faster does not make it faster. Inlining a function with no lambda parameters rarely helps and can bloat your output. Let the use case, lambdas, reified types, or non-local returns, justify the keyword. These distinctions surface often in technical screens, too; the Kotlin interview questions drill more of the same fundamentals.

If you want to go deeper on Kotlin internals, see the guide to Job types in Kotlin Coroutines for another lifecycle-level concept.

Sources

Kotlin keywords inline, crossinline, noinline, reified, and where on a deep-dive cover

El problema que resuelven estas palabras clave

Kotlin hace que las funciones de orden superior y los genéricos parezcan sencillos. Pasas lambdas como si fueran valores y escribes código genérico sin mucha ceremonia. Esa comodidad esconde un coste. Cada lambda que pasas es, por defecto, un objeto que el entorno de ejecución tiene que reservar. Cada parámetro de tipo genérico se borra en tiempo de compilación, así que el tipo que escribiste desaparece antes de que el programa se ejecute.

inline, noinline y crossinline deciden cómo se compilan las lambdas. reified conserva un tipo genérico que la JVM borraría. where permite que un solo parámetro de tipo cumpla varias restricciones a la vez.

¿Qué hace inline?

El modificador inline le dice al compilador que copie el cuerpo de la función, y el de cualquier lambda que le pases, directamente en el punto de llamada. En tiempo de ejecución no hay llamada a función ni objeto lambda. El bytecode se lee como si hubieras escrito la lógica a mano, en línea.

Ojo: inline está sobrecargada. Este artículo trata de las funciones inline. Kotlin reutiliza la palabra para otras dos cosas. Las clases inline (de valor) envuelven un único valor sin reserva en tiempo de ejecución (@JvmInline value class UserId(val raw: String)), y las propiedades inline insertan el código de sus accesores. La misma palabra clave, mecánicas distintas. Todo lo que sigue trata de funciones.

Sin inline, una función que recibe una lambda reserva un objeto Function cada vez que la llamas. En un bucle que se ejecuta mucho, o en una función de ayuda a la que llamas a menudo, esas reservas se acumulan. La documentación oficial es clara con el coste: cada función es un objeto que captura una clausura, y «las reservas de memoria (tanto de objetos función como de clases) y las llamadas virtuales introducen sobrecoste en tiempo de ejecución» (documentación de Kotlin, funciones inline).

inline fun measure(block: () -> Unit) {
    val start = System.nanoTime()
    block()
    println("Took ${System.nanoTime() - start} ns")
}

fun main() {
    measure {
        // This lambda body is copied into main().
        // No Function0 object is allocated.
        (1..1_000).sum()
    }
}

El inlining también permite los retornos no locales. Como el cuerpo de la lambda se pega dentro de quien llama, un return normal dentro de la lambda sale de la función que la envuelve, no solo de la lambda. Por eso forEach de la biblioteca estándar puede hacer esto:

fun findFirstEven(numbers: List<Int>): Int? {
    numbers.forEach {
        if (it % 2 == 0) return it // returns from findFirstEven, not just the lambda
    }
    return null
}

Una advertencia que sale de la experiencia: inline no sale gratis. Copiar el cuerpo de una función grande en muchos puntos de llamada hincha el bytecode. El equipo de Kotlin da el mismo aviso: el inlining «puede hacer que el código generado crezca», y recomienda evitar marcar como inline las funciones grandes (documentación de Kotlin, funciones inline). Resérvalo para funciones pequeñas que reciben lambdas. Marcar como inline una función grande sin parámetros lambda suele hacer más daño que bien, y el compilador te avisará.

¿Cuándo debes usar noinline?

Cuando una función está marcada como inline, todos sus parámetros lambda se inlinean por defecto. A veces eso es un problema. Una lambda inlineada no tiene representación como objeto, así que no puedes guardarla en una variable, meterla en una colección ni pasarla a una función que espera un objeto lambda de verdad. El modificador noinline saca un único parámetro del inlining. Como dice la documentación, «las lambdas noinline… se pueden manipular como quieras, incluso guardarlas en campos o pasarlas de un sitio a otro» (documentación de Kotlin, funciones inline).

inline fun runTasks(
    immediate: () -> Unit,
    noinline deferred: () -> Unit
) {
    immediate()                 // inlined, no allocation
    pendingCallbacks.add(deferred) // needs a real object reference, so noinline
}

val pendingCallbacks = mutableListOf<() -> Unit>()

Aquí immediate sigue inlineada por rendimiento, mientras que deferred se convierte en un objeto lambda normal que puedes dejar en una lista e invocar más tarde. Si intentaras añadir immediate a la lista, el compilador lo rechazaría porque no hay ningún objeto que añadir.

Usa noinline cuando una lambda tenga que sobrevivir a la llamada o viajar a un sitio al que la versión inlineada no puede ir.

¿Qué problema resuelve crossinline?

crossinline mantiene la lambda inlineada, pero le prohíbe los retornos no locales. Lo necesitas cuando la lambda no la llama directamente la función inline, sino que se ejecuta dentro de otro contexto, como una lambda anidada, un objeto anónimo o un Runnable. La documentación describe justo este caso: cuando una función inline llama a una lambda «no directamente desde el cuerpo de la función, sino desde otro contexto de ejecución, como un objeto local o una función anidada», el flujo de control no local deja de estar permitido (documentación de Kotlin, funciones inline).

Un retorno no local solo tiene sentido cuando el cuerpo de la lambda se ejecuta en el marco de quien llama. En el momento en que entregas la lambda a un objeto aparte que se ejecuta más tarde, volver desde la función exterior es imposible. El compilador te obliga a reconocerlo con crossinline.

inline fun runOnThread(crossinline block: () -> Unit) {
    val task = Runnable {
        block() // called from inside the Runnable, a different context
    }
    Thread(task).start()
}

Sin crossinline, esto no compila. El compilador se niega a inlinear block dentro del Runnable porque un return no local ahí no tendría a dónde volver. Marcar el parámetro como crossinline dice «la dejo inline, pero prometo no hacer un retorno no local», y el código compila.

Si llamas a la lambda directamente, con inline basta. Si la envuelves en otro objeto o en otra lambda, necesitas crossinline. Si necesitas guardarla o reenviarla, necesitas noinline. Una misma lambda no puede ser noinline y crossinline a la vez, porque tiran en direcciones opuestas. Los dos modificadores, además, solo existen en funciones inline: noinline y crossinline solo significan algo en un parámetro lambda de una función inline, y el compilador los rechaza en cualquier otro sitio.

¿Cómo vence reified al borrado de tipos?

En la JVM, los argumentos de tipo genérico se borran en tiempo de compilación. La documentación de Kotlin dice que «no hay una forma general de comprobar en tiempo de ejecución si una instancia de un tipo genérico se creó con ciertos argumentos de tipo», así que el compilador prohíbe comprobaciones como list is T (documentación de Kotlin, genéricos: borrado de tipos). El apaño habitual es pasar a mano un parámetro Class<T>, y queda ruidoso.

reified quita ese ruido, pero solo funciona dentro de funciones inline. Como la función se inlinea, el tipo concreto se conoce en cada punto de llamada, y el compilador puede sustituir el tipo real allá donde referencias T.

inline fun <reified T> Any.isInstanceOf(): Boolean = this is T

inline fun <reified T> parseJson(json: String): T =
    Gson().fromJson(json, T::class.java)

// Call site: no need to pass User::class anymore.
val user: User = parseJson(jsonString)

Compáralo con la versión sin reified, en la que escribirías fun <T> parseJson(json: String, clazz: Class<T>) y pasarías User::class.java en cada llamada. reified deja el punto de llamada limpio mientras la información de tipo sobrevive dentro del cuerpo de la función. La documentación confirma que «las funciones normales (no marcadas como inline) no pueden tener parámetros de tipo reified» (documentación de Kotlin, parámetros de tipo reified). Quita el inline y reified deja de compilar.

reified te da is T, as T y T::class, pero no un constructor. No puedes escribir T() para instanciar el tipo, ni llegar al objeto companion de T ni a sus miembros estáticos. Cuando necesites eso, pasa de forma explícita una lambda de fábrica o un argumento KClass<T>. Este patrón exacto aparece en proyectos grandes, como los repositorios genéricos del artículo de arquitectura limpia en Kotlin Multiplatform.

¿Para qué sirve la palabra clave where?

where es la rara del grupo. No tiene nada que ver con el inlining ni con las lambdas. Declara varios límites superiores sobre un parámetro de tipo genérico. Kotlin te deja escribir un único límite en línea, como en <T : Comparable<T>>, pero en cuanto un parámetro de tipo necesita dos o más límites, tienes que moverlos a una cláusula where. La regla está explícita en la documentación: «solo se puede indicar un límite superior dentro de los paréntesis angulares. Si el mismo parámetro de tipo necesita más de un límite superior, hace falta una cláusula where aparte» (documentación de Kotlin, genéricos: límites superiores).

Antes de la restricción, recuerda cómo se declara una función genérica: el parámetro de tipo va delante del nombre de la función, y o lo pasas de forma explícita o dejas que el compilador lo infiera (documentación de Kotlin, funciones genéricas).

// The type parameter <T> goes before the function name.
fun <T> singletonList(item: T): List<T> = listOf(item)

val a = singletonList<Int>(1) // explicit type argument
val b = singletonList(1)      // inferred, same result

Un único límite superior va justo después del parámetro de tipo, dentro de los paréntesis angulares:

// T is restricted to types that are Comparable with themselves.
fun <T : Comparable<T>> greater(a: T, b: T): T = if (a > b) a else b

Ese es el límite: un solo límite superior dentro de los paréntesis. En cuanto un parámetro de tipo necesita dos o más, los mueves a una cláusula where.

// T must be BOTH Comparable<T> and CharSequence at the same time.
fun <T> printSortedLengths(items: List<T>)
    where T : Comparable<T>, T : CharSequence {
    items.sorted().forEach { item -> println(item.length) }
}

Aquí T tiene que ser Comparable<T> para poder ordenar la lista, y CharSequence para que cada elemento exponga .length. Ninguno de los dos límites basta por sí solo; la cláusula where expresa la intersección.

where incluso se combina con las palabras clave de arriba. Una función inline reified puede llevar una cláusula where cuando su argumento de tipo también necesita límites:

// reified lets us filter by T at runtime; where bounds T to Comparable.
inline fun <reified T> smallestOfType(items: List<Any>): T?
    where T : Comparable<T> {
    return items.filterIsInstance<T>().minOrNull()
}

val mixed: List<Any> = listOf("skip", 3, 1, 2, "x")
println(smallestOfType<Int>(mixed)) // 1

Esa única declaración junta tres de las cinco palabras clave: inline hace que se pueda inlinear, reified mantiene T disponible para filterIsInstance, y where restringe T para que minOrNull pueda comparar los elementos.

Comparación rápida

Palabra clave Se aplica a Qué hace ¿Exige inline?
inline función Copia el cuerpo y las lambdas al punto de llamada; elimina la reserva de la lambda; permite retornos no locales no aplica
noinline parámetro lambda Saca una lambda del inlining para poder guardarla o pasarla más adelante Sí
crossinline parámetro lambda Mantiene la lambda inlineada, pero prohíbe los retornos no locales Sí
reified parámetro de tipo Hace que un tipo genérico esté disponible en tiempo de ejecución, venciendo al borrado de tipos Sí
where parámetro de tipo Declara varios límites superiores sobre un genérico No

Cuándo usar cada una: guía de decisión

Tira de inline cuando escribas una función de orden superior pequeña que se ejecuta a menudo y quieras quitar el sobrecoste de reservar la lambda, o cuando necesites retornos no locales. Sáltatela en funciones grandes sin parámetros lambda.

Añade noinline a un parámetro concreto en el momento en que necesites guardar esa lambda, meterla en una colección o pasarla a una función que no es inline. Añade crossinline en su lugar cuando la lambda se invoque desde un contexto anidado, como un Runnable o un objeto anónimo, y quieras mantenerla inlineada.

Tira de reified siempre que te veas pasando un argumento Class<T> solo para rodear el borrado de tipos, y estés dispuesto a marcar la función como inline. Y where solo se gana el sitio cuando un parámetro de tipo necesita más de un límite superior.

Marcar una función como inline porque suena más rápida no la hace más rápida. Inlinear una función sin parámetros lambda rara vez ayuda y puede hinchar el binario. Deja que el caso de uso, las lambdas, los tipos reified o los retornos no locales, justifique la palabra clave. Estas distinciones salen a menudo en las pruebas técnicas; las preguntas de entrevista de Kotlin repasan más de los mismos fundamentos.

Si quieres profundizar en las tripas de Kotlin, mira la guía de los tipos de Job en las corrutinas de Kotlin: otro concepto de ciclo de vida.

Fuentes

คีย์เวิร์ด Kotlin ได้แก่ inline, crossinline, noinline, reified และ where บนปกเจาะลึก

ปัญหาที่คีย์เวิร์ดเหล่านี้แก้

Kotlin ทำให้ higher-order function และ generic รู้สึกง่าย คุณส่ง lambda ไปมาเหมือนค่า และเขียนโค้ด generic โดยไม่ต้องมีพิธีมาก ความสะดวกนั้นซ่อนต้นทุน ทุก lambda ที่คุณส่ง โดยค่าเริ่มต้น เป็นอ็อบเจกต์ที่รันไทม์ต้อง allocate ทุก type parameter แบบ generic ถูกลบตอนคอมไพล์ ดังนั้น type ที่คุณเขียนหายไปก่อนโปรแกรมรัน

inline, noinline และ crossinline ตัดสินว่า lambda ถูกคอมไพล์อย่างไร reified เก็บ generic type ที่ JVM จะลบ where ให้ type parameter ตัวเดียวผ่านข้อจำกัดหลายข้อพร้อมกัน

inline ทำอะไร

ตัวแก้ไข inline บอกคอมไพเลอร์ให้คัดลอกตัวฟังก์ชัน และตัวของ lambda ที่คุณส่งเข้ามัน ไปที่จุดเรียกโดยตรง ไม่มีการเรียกฟังก์ชัน และไม่มีอ็อบเจกต์ lambda ตอนรัน ไบต์โค้ดอ่านเหมือนคุณเขียนลอจิกนั้นแบบ inline ด้วยมือ

ระวัง: inline มีหลายความหมาย โพสต์นี้ครอบคลุม inline function Kotlin ใช้คำเดียวกันกับอีกสองฟีเจอร์ Inline (value) class ห่อค่าเดียวโดยไม่ allocate ตอนรัน (@JvmInline value class UserId(val raw: String)) และ inline property จะ inline โค้ดของ accessor คีย์เวิร์ดเดียวกัน กลไกต่างกัน ทุกอย่างด้านล่างเป็นเรื่องของฟังก์ชัน

ถ้าไม่มี inline ฟังก์ชันที่รับ lambda จะ allocate อ็อบเจกต์ Function ทุกครั้งที่คุณเรียก ในลูปร้อนหรือตัวช่วยที่ถูกเรียกบ่อย allocation เหล่านั้นสะสม เอกสารทางการพูดตรงเรื่องต้นทุน แต่ละฟังก์ชันเป็นอ็อบเจกต์ที่จับ closure และ “memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead” (เอกสาร Kotlin, Inline functions)

inline fun measure(block: () -> Unit) {
    val start = System.nanoTime()
    block()
    println("Took ${System.nanoTime() - start} ns")
}

fun main() {
    measure {
        // This lambda body is copied into main().
        // No Function0 object is allocated.
        (1..1_000).sum()
    }
}

การ inline ยังเปิด non-local return เพราะตัว lambda ถูกแปะเข้าผู้เรียก return ธรรมดาใน lambda จึงกลับจากฟังก์ชันที่ห่ออยู่ ไม่ใช่แค่จาก lambda นั่นคือเหตุผลที่ forEach จากไลบรารีมาตรฐานทำแบบนี้ได้

fun findFirstEven(numbers: List<Int>): Int? {
    numbers.forEach {
        if (it % 2 == 0) return it // returns from findFirstEven, not just the lambda
    }
    return null
}

คำเตือนจากประสบการณ์ inline ไม่ฟรี การคัดลอกตัวฟังก์ชันใหญ่เข้าหลายจุดเรียกทำให้ไบต์โค้ดบวม ทีม Kotlin ให้คำเตือนเดียวกัน โดยบอกว่าการ inline “may cause the generated code to grow” และแนะนำให้เลี่ยงการ inline ฟังก์ชันใหญ่ (เอกสาร Kotlin, Inline functions) เก็บไว้สำหรับฟังก์ชันเล็กที่รับ lambda การ inline ฟังก์ชันใหญ่ที่ไม่มีพารามิเตอร์ lambda มักให้โทษมากกว่าประโยชน์ และคอมไพเลอร์จะเตือนคุณ

ควรใช้ noinline เมื่อไร

เมื่อฟังก์ชันถูกติด inline พารามิเตอร์ lambda ทั้งหมด ของมันถูก inline โดยค่าเริ่มต้น บางครั้งนั่นเป็นปัญหา lambda ที่ถูก inline ไม่มีตัวตนเป็นอ็อบเจกต์ คุณจึงเก็บมันในตัวแปร ใส่ในคอลเลกชัน หรือส่งให้ฟังก์ชันที่ต้องการอ็อบเจกต์ lambda จริงไม่ได้ ตัวแก้ไข noinline ดึงพารามิเตอร์ตัวเดียวออกจากการ inline ตามเอกสาร “noinline lambdas… can be manipulated in any way you like, including being stored in fields or passed around” (เอกสาร Kotlin, Inline functions)

inline fun runTasks(
    immediate: () -> Unit,
    noinline deferred: () -> Unit
) {
    immediate()                 // inlined, no allocation
    pendingCallbacks.add(deferred) // needs a real object reference, so noinline
}

val pendingCallbacks = mutableListOf<() -> Unit>()

ตรงนี้ immediate ยังถูก inline เพื่อประสิทธิภาพ ส่วน deferred กลายเป็นอ็อบเจกต์ lambda ธรรมดาที่คุณซ่อนในลิสต์แล้วเรียกทีหลังได้ ถ้าคุณพยายามใส่ immediate ลงลิสต์ คอมไพเลอร์จะปฏิเสธเพราะไม่มีอ็อบเจกต์ให้เพิ่ม

ใช้ noinline เมื่อ lambda ตัวหนึ่งต้องมีชีวิตยาวกว่าการเรียกฟังก์ชัน หรือต้องเดินทางไปที่ที่เวอร์ชันที่ถูก inline ไปไม่ได้

crossinline แก้ปัญหาอะไร

crossinline คง lambda ไว้แบบ inline แต่ห้าม non-local return จากมัน คุณต้องใช้สิ่งนี้เมื่อ lambda ไม่ถูกเรียกตรงจากฟังก์ชัน inline แต่รันในบริบทการทำงานอีกแบบ เช่น lambda ซ้อน อ็อบเจกต์นิรนาม หรือ Runnable เอกสารอธิบายกรณีนี้ตรงๆ เมื่อฟังก์ชัน inline เรียก lambda “not directly from the function body, but from another execution context, such as a local object or a nested function” การควบคุมแบบ non-local ไม่ได้รับอนุญาตอีกต่อไป (เอกสาร Kotlin, Inline functions)

non-local return มีความหมายเมื่อตัว lambda ทำงานในเฟรมของผู้เรียก พอคุณส่ง lambda ให้อ็อบเจกต์แยกที่รันทีหลัง การกลับจากฟังก์ชันด้านนอกเป็นไปไม่ได้ คอมไพเลอร์บังคับให้คุณยอมรับสิ่งนั้นด้วย crossinline

inline fun runOnThread(crossinline block: () -> Unit) {
    val task = Runnable {
        block() // called from inside the Runnable, a different context
    }
    Thread(task).start()
}

ถ้าไม่มี crossinline อันนี้คอมไพล์ไม่ผ่าน คอมไพเลอร์ปฏิเสธที่จะ inline block ใน Runnable เพราะ return แบบ non-local ตรงนั้นไม่มีที่ให้กลับ การติดพารามิเตอร์เป็น crossinline คือการบอกว่า “inline มัน แต่ฉันสัญญาว่าจะไม่ return แบบ non-local” แล้วโค้ดก็คอมไพล์

ถ้าคุณเรียก lambda โดยตรง inline ธรรมดาก็พอ ถ้าคุณห่อมันในอ็อบเจกต์หรือ lambda อีกชั้น คุณต้องใช้ crossinline ถ้าคุณต้องเก็บหรือส่งต่อ คุณต้องใช้ noinline lambda ตัวเดียวเป็นทั้ง noinline และ crossinline ไม่ได้ เพราะมันดึงคนละทาง ตัวแก้ไขทั้งคู่ยังผูกกับฟังก์ชัน inline เท่านั้น noinline และ crossinline มีความหมายบนพารามิเตอร์ lambda ของฟังก์ชัน inline เท่านั้น และคอมไพเลอร์ปฏิเสธมันที่อื่น

reified ชนะ type erasure อย่างไร

บน JVM อาร์กิวเมนต์ type แบบ generic ถูกลบตอนคอมไพล์ เอกสาร Kotlin ระบุว่า “there is no general way to check whether an instance of a generic type was created with certain type arguments at runtime” ดังนั้นคอมไพเลอร์ห้ามการตรวจแบบ list is T (เอกสาร Kotlin, Generics: type erasure) ทางอ้อมที่คุ้นคือส่งพารามิเตอร์ Class<T> ด้วยมือ ซึ่งเสียงดัง

reified เอาเสียงนั้นออก แต่ใช้ได้เฉพาะในฟังก์ชัน inline เพราะฟังก์ชันถูก inline type จริงจึงรู้ที่ทุกจุดเรียก คอมไพเลอร์จึงแทน type จริงได้ทุกที่ที่คุณอ้าง T

inline fun <reified T> Any.isInstanceOf(): Boolean = this is T

inline fun <reified T> parseJson(json: String): T =
    Gson().fromJson(json, T::class.java)

// Call site: no need to pass User::class anymore.
val user: User = parseJson(jsonString)

เทียบกับเวอร์ชันที่ไม่ได้ reified ซึ่งคุณจะเขียน fun <T> parseJson(json: String, clazz: Class<T>) แล้วส่ง User::class.java ทุกจุดเรียก reified ให้จุดเรียกสะอาด ในขณะที่ข้อมูล type ยังอยู่ถึงในตัวฟังก์ชัน เอกสารยืนยันว่า “normal functions (not marked as inline) cannot have reified type parameters” (เอกสาร Kotlin, Reified type parameters) ตัด inline ออก แล้ว reified จะคอมไพล์ไม่ผ่าน

reified ให้คุณใช้ is T, as T และ T::class แต่ไม่ให้คอนสตรักเตอร์ คุณเขียน T() เพื่อสร้างอินสแตนซ์ของ type ไม่ได้ และเข้าถึง companion object หรือสมาชิก static ของ T ไม่ได้ เมื่อต้องการสิ่งเหล่านั้น ให้ส่ง factory lambda หรืออาร์กิวเมนต์ KClass<T> อย่างชัดเจน คุณจะเจอแพตเทิร์นนี้ในโปรเจกต์ใหญ่ เช่น repository แบบ generic ใน พิมพ์เขียว Clean Architecture ของ Kotlin Multiplatform

คีย์เวิร์ด where ใช้ทำอะไร

where เป็นตัวแปลกในกลุ่มนี้ มันไม่เกี่ยวกับการ inline หรือ lambda มันประกาศ upper bound หลายตัว บน type parameter แบบ generic Kotlin ให้คุณเขียน bound เดียวแบบ inline ได้ เช่น <T : Comparable<T>> แต่เมื่อ type parameter ต้องการ bound สองตัวขึ้นไป คุณต้องย้ายพวกมันไปประโยค where กฎในเอกสารชัดเจน “only one upper bound can be specified inside the angle brackets. If the same type parameter needs more than one upper bound, you need a separate where-clause” (เอกสาร Kotlin, Generics: upper bounds)

ก่อนถึงข้อจำกัด ให้ทวนว่าฟังก์ชัน generic ถูกประกาศอย่างไร type parameter อยู่หน้าชื่อฟังก์ชัน และคุณส่งมันอย่างชัดหรือให้คอมไพเลอร์อนุมาน (เอกสาร Kotlin, Generic functions)

// The type parameter <T> goes before the function name.
fun <T> singletonList(item: T): List<T> = listOf(item)

val a = singletonList<Int>(1) // explicit type argument
val b = singletonList(1)      // inferred, same result

upper bound ตัวเดียวไปต่อจาก type parameter ในวงเล็บมุม

// T is restricted to types that are Comparable with themselves.
fun <T : Comparable<T>> greater(a: T, b: T): T = if (a > b) a else b

นั่นคือเพดาน bound เดียวในวงเล็บ เมื่อ type parameter ต้องการ bound สองตัวขึ้นไป คุณย้ายพวกมันเข้าประโยค where

// T must be BOTH Comparable<T> and CharSequence at the same time.
fun <T> printSortedLengths(items: List<T>)
    where T : Comparable<T>, T : CharSequence {
    items.sorted().forEach { item -> println(item.length) }
}

ตรงนี้ T ต้องเป็น Comparable<T> เพื่อให้ลิสต์เรียงได้ และเป็น CharSequence เพื่อให้แต่ละรายการมี .length bound ตัวเดียวไม่พอ ประโยค where บอกจุดตัดนั้น

where ยังรวมกับคีย์เวิร์ดด้านบนได้ ฟังก์ชัน inline แบบ reified มีประโยค where ได้เมื่ออาร์กิวเมนต์ type ต้องการ bound ด้วย

// reified lets us filter by T at runtime; where bounds T to Comparable.
inline fun <reified T> smallestOfType(items: List<Any>): T?
    where T : Comparable<T> {
    return items.filterIsInstance<T>().minOrNull()
}

val mixed: List<Any> = listOf("skip", 3, 1, 2, "x")
println(smallestOfType<Int>(mixed)) // 1

ประกาศเดียวนี้ดึงสามในห้าคีย์เวิร์ดมาด้วยกัน inline ทำให้ inline ได้ reified คง T ไว้สำหรับ filterIsInstance และ where จำกัด T เพื่อให้ minOrNull เทียบองค์ประกอบได้

เทียบเร็ว

คีย์เวิร์ด ใช้กับ ทำอะไร ต้องมี inline หรือไม่
inline ฟังก์ชัน คัดลอกตัวและ lambda ไปจุดเรียก ตัด allocation ของ lambda เปิด non-local return ไม่เกี่ยวข้อง
noinline พารามิเตอร์ lambda ดึง lambda ตัวหนึ่งออกจากการ inline เพื่อให้เก็บหรือส่งต่อได้ ใช่
crossinline พารามิเตอร์ lambda คง lambda แบบ inline แต่ห้าม non-local return ใช่
reified type parameter ทำให้ generic type ใช้ได้ตอนรัน ต้าน type erasure ใช่
where type parameter ประกาศ upper bound หลายตัวบน generic ไม่

เมื่อไรใช้อะไร: คู่มือตัดสินใจ

หยิบ inline เมื่อคุณเขียน higher-order function เล็กที่รันบ่อย และอยากตัด overhead จาก allocation ของ lambda หรือเมื่อคุณต้องการ non-local return ข้ามมันสำหรับฟังก์ชันใหญ่ที่ไม่มีพารามิเตอร์ lambda

ใส่ noinline ให้พารามิเตอร์ที่ระบุทันทีที่คุณต้องเก็บ lambda นั้น เพิ่มมันเข้าคอลเลกชัน หรือส่งมันให้ฟังก์ชันที่ไม่ได้ inline ใส่ crossinline แทนเมื่อ lambda ถูกเรียกจากบริบทซ้อน เช่น Runnable หรืออ็อบเจกต์นิรนาม และคุณอยากคงมันแบบ inline

หยิบ reified เมื่อคุณพบว่าตัวเองส่งอาร์กิวเมนต์ Class<T> เพียงเพื่อเลี่ยง type erasure และคุณยอมทำให้ฟังก์ชันเป็น inline และ where มีที่เมื่อ type parameter ตัวหนึ่งต้องการ upper bound มากกว่าหนึ่งตัว

การติด inline ให้ฟังก์ชันเพราะฟังดูเร็วขึ้น ไม่ได้ทำให้มันเร็วขึ้น การ inline ฟังก์ชันที่ไม่มีพารามิเตอร์ lambda แทบไม่ช่วย และทำให้เอาต์พุตบวมได้ ให้กรณีใช้งานเป็นตัวตัดสิน คือ lambda, type แบบ reified หรือ non-local return ความแตกต่างเหล่านี้โผล่บ่อยในรอบสัมภาษณ์เทคนิคเช่นกัน คำถามสัมภาษณ์ Kotlin ซ้อมพื้นฐานชุดเดียวกันเพิ่ม

ถ้าอยากเจาะกลไกภายในของ Kotlin ต่อ ดู คู่มือชนิดของ Job ใน Kotlin Coroutines สำหรับแนวคิดระดับวงจรชีวิตอีกเรื่อง

แหล่งข้อมูล

  • JetBrains, เอกสาร Kotlin: Inline functions (ครอบคลุม inline, noinline, crossinline, non-local return และ type parameter แบบ reified), ดึงเมื่อ 2026-06-21, https://kotlinlang.org/docs/inline-functions.html
  • JetBrains, เอกสาร Kotlin: Generics (upper bound, ประโยค where และ type erasure), ดึงเมื่อ 2026-06-21, https://kotlinlang.org/docs/generics.html
Share:Compartir:แชร์:

CommentsComentariosความคิดเห็น

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…