Lambdas & Inline Functions Interview Questions
KOTLIN › Types & Classes
What does the inline keyword do, and why is it useful for higher-order functions?
What a strong answer covers: inline copies the function body and the lambda body into the call site at compile time, so no Function object is allocated and there's no virtual invoke call. That makes things like map, filter and let free in hot paths, and enables non-local returns and reified type parameters.
What are noinline and crossinline, and when do you need them?
What a strong answer covers: noinline marks a lambda parameter of an inline function that must stay a real object, for example because you store it or pass it to a non-inline function. crossinline is for a lambda that will be inlined but called from another context, like inside a Runnable or another lambda, so non-local returns are forbidden in it.
What is a non-local return? Give an example where it surprises people.
What a strong answer covers: Inside a lambda passed to an inline function, a bare return returns from the enclosing function, not just the lambda. list.forEach { if (it == target) return } exits the whole function, which surprises people expecting 'continue'. Use return@forEach to skip one element. In non-inline lambdas a bare return isn't allowed.
When should you NOT mark a function inline?
What a strong answer covers: When it doesn't take lambdas (no allocation to save; the compiler warns), when the body is large and called from many places (bytecode bloat), when it's public API in a library (callers inline the body, so changing it needs them to recompile, and it can't access private members), and when it's recursive.
Lambdas capture variables. What does capturing mean for memory and for Android lifecycles, and how do lambdas compile on the JVM today?
What a strong answer covers: A non-inline lambda that captures a value becomes an object holding a reference to it, so a lambda capturing an Activity, View or Fragment and stored in a long-lived place (a singleton listener, a callback in a repository) leaks that object. Non-capturing lambdas can be a singleton. Since Kotlin 2.0, lambdas compile with invokedynamic (LambdaMetafactory) by default rather than a generated class each. A strong answer gives a concrete leak and fix: unregister, use lifecycle-aware collection, or hold a weak reference.