Function is a group of inter related block of code which performs a specific task. Function is used to break a program into different sub module. It makes reusability of code and makes program more manageable.
In Kotlin, functions are declared using fun keyword. There are two types of functions depending on whether it is available in standard library or defined by user.
Standard Library Function
Kotlin Standard library function is built-in library functions which are implicitly present in library and available for use.
Square root of 25 is 5.0
User defined Function
User defined function is a function which is created by user. User defined function takes the parameter(s), perform an action and return the result of that action as a value.
Kotlin functions are declared using the fun keyword. For example:
We have to call the function to run codes inside the body of the function.
Kotlin simple function example
sum = 11 code after sum
Kotlin Parameterize Function and Return Value
Functions are also takes parameter as arguments and return value. Kotlin functions are defined using Pascal notation, i.e. name:type (name of parameter and its type). Parameters in function are separated using commas.
If a function does not returns any value than its return type is Unit. It is optional to specify the return type of function definition which does not returns any value.
Kotlin parameterize function example