To share this page click on the buttons below;
Functions
Functions are defined in the following way:
fun <function_name>(<argument 1>: <type>, <argument 2>: <type>, ...): <return_type> {
// function body
}
Arguments function can have default arguments in the function declaration. Kotlin supports also named argument so that it is possible to specify in the function call only the name and value of one ore more parameters leaving the other to their default values.
Functions are firts class citizen, that means:
- functions can be stored in variable and data structure
- functions can be passed as argument and returned by high-order function (that is the definition of high-order function, i.e. a function that take function as argument and / or returns function.
Type of a function
val <function_variable>: (<type_argument1>,<type_argument2>,...) -> <return_value>
defines a function that take (<type_argument1>,<type_argument2>,...)
and return <return_value>
.
A function that does not return anything must specify it returns Unit
.
A function type that belongs to an object add a receiver object with dot notation.
val <function_variable>: <receiver_object>.(<type_argument1>,<type_argument2>,...) -> <return_value>
A nullable function type is specified with parenthesis and ?
.
val <function_variable>: ((<type_argument1>,<type_argument2>,...) -> <return_value>)?
Function literals
Function literals are function that are not declared but used directly as expression.
Lambda functions
{ <argument1>, <argument2>, ... -> <function_body> }
defined alway in curly braces. The function body goes after ->
.
The last expression in the body is the return value of the lambda function.
Trailing lambda
if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses ???
Implicit single parameter
If a lambda has a single parameter the parameter is automatically declared as it
.
Anonymous function
Anonymous function allow the declaration of the return type in these 2 forms
fun(<argument1>, <argument2>, ...): <return_type> = <single expression body>
fun(<argument1>, <argument2>, ...): <return_type> {
<multiple expression body>
}
Closures
Lambda expression and anonymous function can access its closure, i.e. the variables declared in the outer scope. The variables captured in the closure can be modified in the lambda.
To share this page click on the buttons below;