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

# Kairo Functions, Methods, and Async Reference

> Complete reference for func, type func, init, async func, and await in Kairo v0.1, including parameter syntax, local bindings, and the return statement.

Functions in Kairo are declared with the `func` keyword and can live at module scope as free functions, or inside a type body as instance methods. This page covers every function-related keyword — `func`, `type func`, `init`, `async func`, and `await` — as well as the local binding keywords `let` and `var` and the `return` statement.

## `func` — Free Functions and Instance Methods

Use `func` to declare a named function. A `func` at module scope is a free function; a `func` inside an `object` or `value` body is an instance method and receives an implicit `this` reference.

**Syntax:**

```kairo theme={null}
func name(param: Type, param2: Type): ReturnType {
    // body
}
```

* All parameters are named.
* In v0.1, parameters are either all positional or all named at the call site — you cannot mix styles.
* The return type follows `:` after the parameter list. Omit the return type annotation for functions that return nothing (void).

```kairo theme={null}
// Free function at module scope
func add(a: Int32, b: Int32): Int32 {
    return a + b
}

// Instance method inside an object
public object Cart {
    var total: Decimal

    init(initial: Decimal) {
        this.total = initial
    }

    func addItem(price: Decimal) {
        this.total = this.total + price
    }

    func getTotal(): Decimal {
        return this.total
    }
}
```

## `type func` — Type-Owned Functions

A `type func` belongs to the type itself rather than to any instance. It has no `this` receiver and is called directly on the type name.

**Syntax:**

```kairo theme={null}
type func name(param: Type): ReturnType {
    // body
}
```

* Declared inside a `value` or `object` body.
* Called as `TypeName.methodName(...)`.
* Cannot access instance members because there is no `this`.

```kairo theme={null}
public value Email {
    address: Text

    type func parse(input: Text): Result<Email, ParseError> {
        // validation logic
        if input.contains("@") {
            return Result.success(Email { address: input })
        }
        return Result.failure(ParseError { message: "Invalid email" })
    }
}

let result: Result<Email, ParseError> = Email.parse("user@example.com")
```

<Tip>
  Use `type func` for factory methods, named constructors, and utility functions that logically belong to a type but do not operate on a specific instance.
</Tip>

## `init` — Object Initialiser

Every `object` has exactly one `init` in v0.1. The `init` sets up the initial state of the object by assigning values to `this.member`.

**Syntax:**

```kairo theme={null}
init(param: Type, param2: Type) {
    this.member = param
}
```

* Always called with named arguments at the call site: `TypeName(param: value)`.
* The `init` body may only contain assignments to `this` members and calls to other initialisation helpers.
* Only one `init` per `object` is allowed in v0.1.

```kairo theme={null}
public object Invoice {
    var number: Text
    var total: Decimal

    init(number: Text, total: Decimal) {
        this.number = number
        this.total = total
    }
}

let inv: Invoice = Invoice(number: "INV-001", total: 299.99)
```

<Note>
  Named-argument call syntax at the `init` call site is mandatory. Positional construction (e.g., `Invoice("INV-001", 299.99)`) is not valid.
</Note>

## `async func` — Suspendable Functions

Mark a function with `async` to declare that it may suspend while waiting for an asynchronous result. An `async func` can contain `await` expressions.

**Syntax:**

```kairo theme={null}
async func name(param: Type): ReturnType {
    // body may contain await
}
```

* An `async func` must be called with `await` at the call site.
* Calling an `async func` without `await` is a compile-time error.

```kairo theme={null}
async func fetchUserName(userId: Text): Text {
    let profile: UserProfile = await UserService.getProfile(userId)
    return profile.name
}
```

## `await` — Explicit Suspension Point

Use `await` to suspend execution until an asynchronous operation completes. Every suspension is explicit — Kairo does not automatically promote synchronous calls into async contexts.

**Syntax:**

```kairo theme={null}
let result = await someAsyncFunc(param: value)
```

**Rules:**

* `await` may only appear inside an `async func`.
* `await` does **not** unwrap a `Result` — it only suspends the current function until the awaited operation resolves.
* If the awaited function returns `Result<T, E>`, you still need to inspect `.isSuccess` or pattern-match the result yourself.

```kairo theme={null}
async func processOrder(orderId: Text): Result<Order, OrderError> {
    let fetched: Result<Order, OrderError> = await OrderRepo.find(orderId)
    if fetched.isFailure {
        return fetched
    }
    let order: Order = fetched.value
    // process order...
    return Result.success(order)
}
```

<Warning>
  `await` does not unwrap `Result`. After awaiting, check `.isSuccess` or `.isFailure` before accessing `.value` or `.error`. Accessing the wrong side is a fault.
</Warning>

## `let` — Immutable Local Binding

Use `let` to declare an immutable local variable. Once bound, the value cannot be reassigned.

```kairo theme={null}
let name: Text = "Kairo"
let count = 42          // type inferred as Int32
let price: Decimal = 9.99
```

* The type annotation is optional when the compiler can infer it from a simple literal or obvious expression.
* Attempting to reassign a `let` binding is a compile-time error.

## `var` — Mutable Local Binding

Use `var` to declare a local variable whose value can be reassigned. An explicit type annotation is required in v0.1.

```kairo theme={null}
var total: Int32 = 0
total = total + 1

var label: Text = "pending"
label = "confirmed"
```

<Note>
  Local `var` bindings always require an explicit type in v0.1. Type inference for mutable locals is planned for a future release.
</Note>

## `return` Statement

Use `return` to exit a function and optionally produce a value. In a void function, a bare `return` exits early. In a function with a return type, `return` must be followed by an expression of the declared type.

```kairo theme={null}
func clamp(value: Int32, min: Int32, max: Int32): Int32 {
    if value < min {
        return min
    }
    if value > max {
        return max
    }
    return value
}
```

```kairo theme={null}
func logIfPositive(n: Int32) {
    if n <= 0 {
        return   // early exit, no value
    }
    Pulse.Console.out.writeLine(n)
}
```

## Complete Example

The following module demonstrates free functions, instance methods, a `type func`, and an `init` together.

```kairo theme={null}
module My.App.Domain

import Pulse.Console

public value Discount {
    percent: Decimal

    type func none(): Discount {
        return Discount { percent: 0.0 }
    }
}

public object PriceCalculator {
    var basePrice: Decimal

    init(base: Decimal) {
        this.basePrice = base
    }

    func apply(discount: Discount): Decimal {
        let reduction: Decimal = this.basePrice * (discount.percent / 100.0)
        return this.basePrice - reduction
    }
}

func main() {
    let calc: PriceCalculator = PriceCalculator(base: 100.0)
    let none: Discount = Discount.none()
    let final: Decimal = calc.apply(none)
    Pulse.Console.out.writeLine(final)
}
```
