Functions
To declare a function in Kotlin you need to use the keyword ‘fun’. Functions can have parameters using Pascal notification (name: type). These parameters can be default arguments, these are used when a corresponding argument is omitted to reduce the number of overloads. To define a default argument, you need to type ‘=’ before the type. Also functions can return values let see the structure of a functions.
The Unit value is a type with only one value: Unit, and this value doesn’t have to be returned explicitly.
Single expression functions: when a functions return a single expressions and the body can be written after ‘=’ omitting the curly braces.
A parameter of a function marked with the vararg modifier means that the parameter can be a variable number of argument to be passed like:
Allowing a variable number of arguments to be passed to the function:
This operator may be the last argument and it can be only one in the function also we can pass a list of arguments one-by-one. If it is already defined, just use spread operator ‘*’.The next expression means the same than the last one.
Functions marked with infix keywords means that is using the inflix notation, this functions can omitting the dot and the parentheses for the calls and have to follow the next requirements:
- Must be members functions or extension functions
- Must have a single parameter
- The parameter mustn’t accept variable number os argument and haven’t default values.
Be careful¡, the infix functions calls have lower precedence than the arithmetic operators, type casts, and the ‘rangeTo’ operator and higher precedence than Boolean operators is-and in check.
Other interesting thing is that when you are calling a method on the current receiver you can use ‘this’.
Function scope
In languages such us Java or C# functions can be declared at top level in a file to don’t create a class to hold a function, in addition Kotlin functions can be declared local, a function inside another function.
Functions already defined inside a class or object are a member functions like in java.
Generic functions are these functions which parameters are specified with angle brackets before the function name.
The tail recursion allows some algorithms be written using loops to instead be written using a recursive function, but without the risk of stack overflow, these functions are marked with tailrec modifier. This is an example of tailrec:
Instead of the traditional style: