Lambdas & Inline Functions Flashcards

KOTLIN › Types & Classes

What does the inline modifier actually do at the call site?
The compiler copies the function's body, and the bodies of its lambda parameters, directly into the call site. No function object or closure is allocated and no virtual invoke happens, so the lambda runs with zero indirection overhead.
What is a non-local return, and why do inline functions allow it?
A non-local return is a bare return inside a lambda that returns from the enclosing function, not just the lambda. It works only with inline functions because the lambda body is inlined into the caller, so the return is a plain return of the outer function.
What does crossinline do and when do you need it?
crossinline keeps a parameter inlined but forbids non-local returns from it. You need it when the lambda is not called directly in the inline function body but inside another execution context, like an object or nested lambda (e.g. a Runnable), where a non-local return would be illegal.
What does noinline do and why use it?
noinline opts a single lambda parameter out of inlining inside an otherwise inline function. You need it when you must treat that lambda as a real object, for example storing it in a field, returning it, or passing it to a non-inline function.
What is a closure in Kotlin and how does it differ from Java lambdas?
A closure is a lambda or local function that captures variables from its enclosing scope. Unlike Java, Kotlin can capture and mutate a var from the outer scope; the captured variable is not required to be final/effectively final.
What are reified type parameters and what requires them?
A reified type parameter makes the generic type available at runtime, so you can do is T, as T, or T::class without passing a Class<T>. It is only allowed on inline functions, because the type is substituted at each inlined call site.
Explain trailing-lambda syntax and the it parameter.
If a function's last parameter is a function type, the lambda can go outside the parentheses; if it is the only argument the parentheses can be dropped entirely. A single-parameter lambda can omit the parameter list and reference the argument as it.
When does inlining hurt rather than help?
Inlining duplicates the body at every call site, so inlining a large function or one called from many places bloats bytecode and can hurt instruction-cache and code size. It pays off for small functions with lambda parameters on hot paths, not as a blanket optimization.
Why can a public inline function not reference private/internal declarations?
Because the inline body is copied into other modules' compiled code, a non-public symbol it uses would be inaccessible there and break binary compatibility. Mark the needed internal declaration @PublishedApi internal to use it from a public inline function.

Back to Lambdas & Inline Functions