Skip to content

06 · Functions

Expression function bodies

Use = expression for a small function or method. The expression supplies the return value, while return, Result propagation, generics and defaults keep the same function semantics as a block body.

On this page

Use = expression for a small function or method. The expression supplies the return value, while return, Result propagation, generics and defaults keep the same function semantics as a block body.

Complete example

Expression function bodies.

21-expression-bodies.zolo
Playground
// Feature: Expression-bodied functions and methods

// Syntax: fn name(parameters) -> Type = expression

// When to use: a small calculation, branch, forwarding call or method.


fn double(x: int) -> int = x * 2
fn absolute(x: int) -> int = if x < 0 { -x } else { x }
fn increment(value: int = 3) -> int = value + 1;
fn identity<T>(value: T) -> T = value

struct Counter(value: int) {
  fn next(self) -> int = self.value + 1
}

fn read_positive(value: int) -> Result<int, str> =
  if value > 0 { .Ok(value) } else { .Err("positive value required") }

// Question-mark failures exit this function; success is explicitly wrapped.

fn checked_double(value: int) -> Result<int, str> = .Ok(double(read_positive(value)?))

print(double(4)) // expected: 8

print(absolute(-7)) // expected: 7

print(increment()) // expected: 4

print(identity("Ada")) // expected: Ada

let counter: Counter = .{ value: 9 }
print(counter.next()) // expected: 10

match checked_double(5) {
  .Ok(value) => print(value),
  .Err(error) => print(error)
} // expected: 10

match checked_double(-1) {
  .Ok(value) => print(value),
  .Err(error) => print(error)
} // expected: positive value required

Rules and behavior

Function parameters and lambdas · Documentation

From a checkout of the repository:

zolo examples/features/05-functions/21-expression-bodies.zolo

Global index

Find your way through Zolo

Try an idea

Start here

9 results

9 results

enespt-br