Functions¶
A function gives a reusable task a name. Declare it with fun, describe the values it accepts, and give its return type when it produces a result.
At a glance
- Declare a function with
fun, typed parameters, and a return type. - Leave out the return type when the function produces no value.
Explore this topic¶
Defining and calling¶
fun, then the name.- Parameters are
name: type, comma-separated. : ReturnTypefollows the parameter list.
The return type is optional for functions that return nothing, so these are equivalent:
Returning a value¶
Use return. Dream checks that every path returns when the return type is not void:
fun clamp(value: int, lo: int, hi: int): int {
if value < lo {
return lo;
}
if value > hi {
return hi;
}
return value;
}
In a void function a bare return; exits early:
Functions can call themselves — recursion works as expected:
Public functions and entry point¶
Functions are file-private by default. Mark one public to import it from other files and export it to the WebAssembly host (see Imports). A public function cannot expose a non-public class:
// public fun make(): Secret { ... } // error if Secret is not public
public fun compute(n: int): int {
return n * n;
}
The runtime starts a program by calling main. Every runnable program needs one; its return type can be omitted: