Functions
Functions in Nubo can be declared by name or created inline as values.
Named Functions
Section titled “Named Functions”Use the fn keyword to declare a function:
fn add(a: int, b: int) int { return a + b}
println(add(2, 3))Void Functions
Section titled “Void Functions”Use void when a function does not return a value:
fn say(message: string) void { println(message)}
say("Hello")Anonymous Functions
Section titled “Anonymous Functions”Anonymous functions can be assigned to variables or passed as arguments:
let add = fn(a: int, b: int) int { return a + b}
println(add(1, 2))They are especially useful for callbacks:
let total: int = 0
let data = bytes("hello")
let codes = data.map(fn(value: byte) int { return int(value)})
codes.each(fn(n: int) void { total = total + n})
println(total)Returning Values
Section titled “Returning Values”Use return to return a value from a function:
type hasLen: iface { length() int}
fn length(obj: hasLen) int { return obj.length()}Function Parameters
Section titled “Function Parameters”Parameters are written with a name and type:
fn greet(name: string) void { println("Hello", name)}Interface Parameters
Section titled “Interface Parameters”A function can accept any value matching an inline interface:
type hasLen: iface { length() int}
fn len(obj: hasLen) int { return obj.length()}
const name: string = "John"println(len(name))Defaults and named arguments
Section titled “Defaults and named arguments”fn greet(name: string = "World", suffix: string = "!") string { return "Hello, " + name + suffix}
println(greet())println(greet(suffix: "!!", name: "Ada"))Struct constructors also support named arguments. See Constructors and init for explicit and automatic initializers. A void call has no ordinary value; call it for its effects rather than assigning its result.