> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Kotlin Anonymous Function

An anonymous function in Kotlin is a function definition that omits the function name and is evaluated as an expression. It serves as an alternative to lambda expressions, specifically designed to allow explicit declaration of the return type and to enforce local `return` control flow semantics.

## Syntax

The syntax of an anonymous function closely mirrors a standard function declaration, but without the identifier. It can be defined using either a block body or an expression body.

**Block Body Syntax:**

```kotlin theme={"dark"}
val multiply = fun(x: Int, y: Int): Int {
    return x * y
}
```

**Expression Body Syntax:**

```kotlin theme={"dark"}
val multiply = fun(x: Int, y: Int): Int = x * y
```

## Syntactic Differences from Lambdas

While anonymous functions and lambdas both resolve to function types, anonymous functions enforce stricter syntactic rules regarding parameters and argument passing:

* **No Trailing Closure Syntax:** Unlike lambdas, an anonymous function cannot be passed outside the parentheses of a higher-order function call. It must always be passed as a standard argument *inside* the parentheses.

```kotlin theme={"dark"}
val list = listOf(1, 2, 3)

// Valid: Passed inside parentheses
list.filter(fun(x) = x > 0)

// Syntax Error: Cannot be placed outside parentheses
// list.filter fun(x) = x > 0
```

* **No Implicit `it` Parameter:** Anonymous functions do not support the implicit `it` parameter for single-parameter functions. Even if the compiler can infer the parameter type, the parameter name itself must always be explicitly declared.

```kotlin theme={"dark"}
// Valid: Explicit parameter name 'item'
list.map(fun(item) = item * 2)

// Syntax Error: 'it' is not implicitly generated for anonymous functions
// list.map(fun() = it * 2)
```

## Type Inference Rules

* **Parameters:** If the anonymous function is passed as an argument to another function, its parameter types can be inferred from the context and may be omitted (though the parameter *names* must still be declared). If assigned to a variable without an explicit type declaration, parameter types must be specified.
* **Return Type:** For expression-body anonymous functions, the return type is inferred automatically. For block-body anonymous functions, the return type must be explicitly declared unless it is `Unit`.

```kotlin theme={"dark"}
// Parameter type inferred from the context of `filter`, but name 'item' is required
val positiveNumbers = listOf(-1, 2, -3, 4).filter(fun(item) = item > 0)
```

## Control Flow and Return Semantics

The most significant mechanical difference between an anonymous function and a lambda expression lies in how the `return` keyword behaves.

In Kotlin, a `return` statement without a label always returns from the nearest enclosing function declared with the `fun` keyword.

* **Inside a Lambda:** A bare `return` inside a lambda expression returns from the enclosing named function (a non-local return), provided the higher-order function taking the lambda is marked as `inline`.
* **Inside an Anonymous Function:** Because an anonymous function is declared using the `fun` keyword, a bare `return` statement resolves to the anonymous function itself. It triggers a local return, yielding a value back to the caller of the anonymous function without exiting the outer enclosing function.

```kotlin theme={"dark"}
fun demonstrateReturnSemantics() {
    val numbers = listOf(1, 2, 3, 4, 5)

    // Using an anonymous function
    numbers.forEach(fun(value) {
        if (value == 3) return  // Local return: exits the anonymous function only
        print(value)            // Output: 1245
    })
    
    println(" - End of function") // This line WILL execute
}
```

## Invocation

Because anonymous functions are expressions that resolve to function types (e.g., `(Int, Int) -> Int`), they are invoked exactly like lambdas or standard function references, using the `invoke()` operator or parentheses.

```kotlin theme={"dark"}
val greet = fun(name: String): String = "Hello, $name"

// Invocation
val message1 = greet("System")
val message2 = greet.invoke("Admin")
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Kotlin Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
