Home »
Kotlin
Functions in Kotlin programming language
By IncludeHelp Last updated : December 04, 2024
Kotlin Functions
Functions are set of instructions that take some input and generate some output. The function is used to perform some specific task.They are useful when we have to repeat some piece of code many times. Every Kotlin program contains a main Function.
Defining a Function
In Kotlin we define a function by using fun keyword, then followed by function name with parameter names. Parameters in Kotlin are defines using Pascal notation i.e. name : Type. Multiple parameters are separated by commas. After that, we specify the return type of the function.
Syntax
fun add(a:Int,b:Int):Int{
return a+b;
}
In this function, we have defined a function add which takes two Integer type parameter a and b and returns the addition (a+b) of Integer type.
Calling Function
Then we can call the function as follows,
var result = add(10, 20)
Single Expression Functions
When a function contains/returns only a single expression then the curly braces can be removed and single expression can be specified after = sign.
fun substract(a:Int, b:Int) = a-b
Default Argument
We can also define function with default parameter.Default values are defined using the = sign after type along with the default value.
fun def Add(a:Int=10,b: Int):Int{
return a+b;
}
Calling function always treats arguments with sequence as they appear in function definition so if we write like,
var result = def Add(10))
will be treated as def Add(a=10) and will produce error. So we have to provide named arguments in such cases.
var result = def Add(b=10))
Unit Returning Function
If function does not return any value then its return type is Unit.
fun name(name:String):Unit{
print(name)
// return Unit is optional
}
This function does not need to return 'Unit' explicitly. Returning 'Unit' is optional.
The return type 'Unit' can also be Omitted from function definition. So the simplest form looks like,
fun name(name:String){
print(name)
}
Kotlin Function Example
package Basic
fun add(a:Int,b:Int):Int{
return a+b;
}
fun substract(a:Int,b:Int)=a-b
fun defAdd(a:Int=10,b: Int):Int{
return a+b;
}
fun name(name:String){
print(name)
}
fun main(arg:Array<String>){
var result=add(10,20)
println(result)
result = substract(20,10)
println(result)
result=defAdd(b=10)
println(result)
name("Aman")
}
Output
30
10
20
Aman