Function definitions
Functions
You can declare a new function using a function statement.
If you omit the argument type for a function, it is assigned the type primitive.
The return type of a function is inferred from its body. It is also possible to specify it explicitly:
All functions must return some value. Functions with explicitly declared return types can call themselves recursively.
For short function that immediately return a value, you can omit the curly braces and the return keyword and instead use the lambda arrow syntax:
Self functions
The first argument of a function may be decorated with the self keyword, turning the function into a self function. When calling a self function, the first argument may be supplied using dot notation:
Lambda expressions
A lambda expression is a terse syntax for creating anonymous function values. A lambda expression is written using an argument list followed by a lambda arrow and a single return expression.
For single-argument lambda expressions, the parantheses around the argument list may be omitted:
Typically used in conjunction with the Seq module, lambda expressions provide the benefit of inferring their argument types from the context:
Advanced: Generic functions
A generic function leaves some of its constituent types – argument types or return type – purposely undefined, replacing them with type variables. This allows the function to operate on different kinds of values while retaining type safety.
In the following example, the function second is defined with one type variable called T, declared in the angle brackets after the function name. This makes the function return number? when called on a list of numbers, text? when called on a list of texts, etc.
Last updated