A function is a group of related lines of code that perform a specific task. Functions help to break down complex computer programs into smaller chunks of commands. This makes computer programs easily managed and enables code reusability.
An example of defining a function in Kotlin is as follows:
fun main() {println("Hello World!")}
In Kotlin, functions are first-class. This means that they’re independent of classes and can be stored in variables or data structures. They can also be passed as arguments to functions or returned by other functions.
There are two types of functions in Kotlin:
Some examples of Kotlin standard library functions are as follows:
main()
print()
println()
arrayOf()
min()
max()
sqrt()
More examples of Kotlin standard library functions can be found here.
Let’s look at the components of a function in Kotlin:
The fun
keyword is used to define a function in Kotlin.
The function name is followed immediately by the fun
keyword, which describes the function’s task.
The parenthesis is used for the parameters of the function. This could contain none, one, or more parameters of the function.
The return type follows immediately after the parameter list. Every function must have a return type. If not explicitly stated, then Kotlin assigns a Unit
return type to the function.
The opening and closing curly braces are used to contain the function’s body, which implements the specific task of the function.
fun multiply(firstNum : Int, secondNum : Int) : Int {return firstNum * secondNum}fun main(){println("The multiply function would return 6 if numbers 2 and 3 are used as the funtion parameters")}
Functions have an independent existence. Functions can be defined outside of the class, whereas methods depend on objects and are defined within the class.
Functions are defined in
Functions are self-describing units of code and do not have any reference variables, whereas methods are called using reference variables.
Therefore, while every method is a function, not every function is a method.