Functions
Characteristic
Some of the function characteristic in Kotlin are:
Returning as value
Can be passed as an arguments
Can be assigned to a variable
Can be stored in data structure
Can be declared in top of file (not necessarily a member of a class)
Can have default arguments & named arguments
Declaration
Declared using fun
keyword, followed by function name, followed by list of parameters inside parentheses (paramName: paramType)
, optionally followed by : returnType
(by default returns Unit
), then the function body inside { .. }
Default arguments
Function parameters can have default values, so when you call the function, by default you don't have to specify a value for those parameters.
Tips: It is recommended that the parameters with default values are the last ones in the list of parameters, otherwise the default values can be used only when calling the function with named arguments.
Named arguments
When named arguments are used, the position order of their declaration can be changed.
Types of functions
Generic functions
Functions can have generic parameters, which are specified using angle brackets <>
before the function name.
Higher Order Function
Is a function that takes function as an parameters, or returns a function
Extension functions
Infix functions
Must be declared as class member / extension function
Must have single parameter
No default argument
The paramaters must not varargs
Last updated
Was this helpful?