Explain Kotlin Function | Kotlin Tutorial
Explain Kotlin Function | Kotlin Tutorial
In this article, you will learn about the functions of kotlin and its types.
The function is a block of code that performs a specific task. It divides the program into a small sub-module. Functions increase the reusability of the program and make it well organized. The fun keyword is used to declare the function in the kotlin language.
There are two types of functions in kotlin similar to the other programming languages.
- Standard library function
- User-defined functions
Standard library functions
Standard library functions are those functions that are already present in the library of the programming language that means implicitly present in the library. It can be used anytime, anywhere. There is no need to declare the function first before using it. The programmer only needs to declare the library at the top of the program to access its function or it can also be accessed with the (.) operator.
Syntax:
library_name.function()
Example:
fun main(args: Array<String>){
var num = 16
var output = Math.sqrt(number.toDouble())
print("Square root of $num is $output")
}
The output of the function is:
Square root of 16 is 4.0
In this, we have to library functions:
- sqrt() is the library function that falls under the library math
- print() is the library function that is used to display the output.
User-defined functions
It is a user-defined function. It means the user has to define the function before using it in a program. It takes the parameter, performs an action, and returns the result.
We need to use the fun keyword to declare a function.
Syntax:
fun function_name(){
# block of code
}
Example:
fun main(args: Array<String>){
mul()
print("Multiplication Done")
}
fun mul(){
var num1 =5
var num2 = 6
println("Multiplication = "+(num1+num2))
}
Here we have created the user-defined function mul() and called it in the main function.
The output of this function is:
Multiplication = 30
Multiplication Done
To use the function in the program, we have to call the function with function_name.
function_name()
Parameterized function and return type
User-defined functions also take parameters and return values. The parameters are separated by commas, and use colon(:) between name and its type. If the function is not returning any value, then its return type is “Unit”. The return type of function can also be defined but it is optional.
Syntax:
fun function_name(parameter:data_type, parameter:data_type){
#body of the function
}
function_name(parameter1, parameter2)