Defining Function and Its Type Kotlin Program

Definition

A function is a block of code written to perform a task. A function may be a parameterized function or a parameter-less function. A function may return a value or it may not return a value. The name of a function starts with a small letter and then follows CamelCase. A function can be declared in many ways and are described below

Syntax

fun method_name(){
//Functionality code
}

OR

fun method_name(variable_name:data_type):return_type{
//Functionality code
}

OR

fun method_name(variable_name:data_type){
//Functionality code
}

Defining Function Example Program

fun main(args: Array < String > ) {
    println("Output from multiplyFunctionOne is : " + multiplyFunctionOne(3, 5))
    println("Output from multiplyFunctionTwo is : " + multiplyFunctionTwo(4, 5))
    multiplyFunctionThree(5, 5)
    multiplyFunctionFour(6, 5)
}

//Function with two Int inputs and Int return type
fun multiplyFunctionOne(a: Int, b: Int): Int {
    return a * b
}

//Function with two Int inputs and Result is returned without mentioning return type
fun multiplyFunctionTwo(a: Int, b: Int) = a * b

//Function with two Int inputs and Unit return type
fun multiplyFunctionThree(a: Int, b: Int): Unit {
    println("Multiplication of $a and $b is ${a * b}")
}

//Function with Unit return type need not be mentioned and can be declared like below
fun multiplyFunctionFour(a: Int, b: Int) {
    println("Multiplication of $a and $b is ${a * b}")
}

Sample Output

Output from multiplyFunctionOne is : 15
Output from multiplyFunctionTwo is : 20
Multiplication of 5 and 5 is 25
Multiplication of 6 and 5 is 30