Expression Bodies (=> print(x))

Expression Bodies (=> print(x))

Luma supports a concise way to define simple functions using expression bodies. These are functions whose entire implementation is a single expression.

Basic Form

fn add(a: int, b: int) -> int => a + b

This is exactly equivalent to:

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

When to Use

Expression bodies are ideal when:

  • The function returns directly from one expression
  • The function would otherwise contain only one return statement
  • Simplicity improves readability

Examples:

fn square(x: float) -> float => x * x

fn greet(name: str) -> str => "Hello, ${name}!"

fn is_even(x: int) -> bool => x % 2 == 0

What They Cannot Do

Expression-bodied functions cannot:

  • Contain multiple statements
  • Declare local variables
  • Include conditionals or loops
  • Perform side effects before returning

x Not allowed:

fn bad(a: int) -> int =>
    if a > 0 { a } else { -a }   // ERROR

Use a block instead:

fn abs(a: int) -> int {
    if a > 0 {
        return a
    }
    return -a
}

Print Example

fn announce(x: str) => print("Value: ${x}")
Last updated on