Skip to main content
The return expression in Kotlin is a control flow construct that immediately terminates the execution of the innermost enclosing function or anonymous function, yielding a specified value to the caller. In Kotlin’s type system, return is an expression that evaluates to the bottom type Nothing. This signifies that the expression never completes normally, allowing it to be used in contexts expecting any arbitrary type.

Syntax

Evaluation and Type Mechanics

Because return evaluates to Nothing, it can be used as an operand in expressions (such as the Elvis operator) without causing type mismatches. The compiler statically determines that any code following a return expression in the same control flow branch is unreachable.

Scope and Resolution

The execution target of a return expression depends strictly on its lexical context, the fun keyword, and the presence of labels.

Unlabeled Returns

An unlabeled return always terminates the nearest enclosing function declared with the fun keyword.

Non-Local Returns

When an unlabeled return expression is used inside a lambda expression passed to an inline higher-order function, it performs a non-local return. It bypasses the lambda’s scope and terminates the nearest enclosing fun.
Note: Unlabeled returns are syntactically prohibited inside lambdas passed to non-inline functions because the compiler cannot guarantee the call stack or execution context of the lambda.

Labeled Returns

To terminate a lambda expression without exiting the enclosing function, a labeled return is required. The label explicitly defines the execution scope to terminate, effectively acting as a local return for the lambda.
Kotlin provides implicit labels that match the name of the higher-order function to which the lambda is passed, eliminating the need for explicit label declarations.

Anonymous Functions

Unlike lambdas, anonymous functions are explicitly declared using the fun keyword. Consequently, an unlabeled return inside an anonymous function resolves to the anonymous function itself, not the enclosing function.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More