Function Declarations
Functions can be declared by using the fun keyword, followed by the name of the declaration, the parameters, the optional return type, and the code that should be executed when the function is called.
The parameters need to be enclosed in parentheses. The return type, if any, is separated from the parameters by a colon (:). The function code needs to be enclosed in opening and closing braces.
Each parameter must have a name, which is the name that the argument value will be available as within the function.
An additional argument label can be provided to require function calls to use the label to provide an argument value for the parameter.
Argument labels make code more explicit and readable. For example, they avoid confusion about the order of arguments when there are multiple arguments that have the same type.
Argument labels should be named so they make sense from the perspective of the function call.
Argument labels precede the parameter name. The special argument label _ indicates that a function call can omit the argument label. If no argument label is declared in the function declaration, the parameter name is the argument label of the function declaration, and function calls must use the parameter name as the argument label.
Each parameter needs to have a type annotation, which follows the parameter name after a colon.
Function calls may provide arguments for parameters which are subtypes of the parameter types.
There is no support for optional parameters, i.e. default values for parameters, and variadic functions, i.e. functions that take an arbitrary amount of arguments.
// Declare a function named `double`, which multiples a number by two.
//
// The special argument label _ is specified for the parameter,
// so no argument label has to be provided in a function call.
//
fun double(_ x: Int): Int {
return x * 2
}
// Call the function named `double` with the value 4 for the first parameter.
//
// The argument label can be omitted in the function call as the declaration
// specifies the special argument label _ for the parameter.
//
double(2) // is `4`It is possible to require argument labels for some parameters, and not require argument labels for other parameters.
The order of the arguments in a function call must match the order of the parameters in the function declaration.
Functions can be nested, i.e., the code of a function may declare further functions.
Last updated
Was this helpful?