Functions

Functions in Kode are first-class citizens. They can be assigned to variables, passed as arguments, and returned from other functions.

Function Declaration

Functions are declared using the fn keyword:

kode
fn greet(name: string) {
    print("Hello, " + name)
}

fn add(a: int, b: int) -> int {
    return a + b
}

Parameters and Return Types

Function parameters specify their types, and return types are optional:

kode
// No return type (returns void)
fn log(message: string) {
    print("[LOG] " + message)
}

// Explicit return type
fn multiply(x: int, y: int) -> int {
    return x * y
}

// Multiple parameters
fn calculate(a: int, b: int, operation: string) -> int {
    if operation == "add" {
        return a + b
    } else if operation == "multiply" {
        return a * b
    }
    return 0
}

Function Calls

kode
greet("World")  // Prints: Hello, World

let result = add(5, 3)  // result = 8
print(result)  // Prints: 8

let calc = calculate(10, 5, "multiply")  // calc = 50

Closures

Functions can capture variables from their surrounding scope:

kode
fn makeAdder(x: int) -> fn(int) -> int {
    return fn(y: int) -> int {
        return x + y
    }
}

let add5 = makeAdder(5)
let add10 = makeAdder(10)

print(add5(3))   // Prints: 8
print(add10(3))  // Prints: 13

Anonymous Functions

You can create anonymous functions without names:

kode
let square = fn(x: int) -> int {
    return x * x
}

let numbers = [1, 2, 3, 4, 5]
let squares = numbers.map(square)
// squares = [1, 4, 9, 16, 25]

Recursion

Functions can call themselves recursively:

kode
fn factorial(n: int) -> int {
    if n <= 1 {
        return 1
    }
    return n * factorial(n - 1)
}

print(factorial(5))  // Prints: 120