Simple Function Example 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.

Syntax

fun method_name(){
//Functionality code
}

Function Example Program

fun main(args: Array < String > ) {
    val num1 = 11
    val num2 = 6

    //Calling function with no parameters and return type
    print()
    //Calling function with 2 parameters num1 and num2 and assigning the result to num3
    val num3 = add(num1, num2)

    //Printing result
    println("After addition of num1 and num2, the result is : " + num3)
}

//Function with parameters and Int return type
fun add(i: Int, j: Int): Int {
    return i + j
}

//Function without parameters and no return type
fun print() {
    println("I am inside print function.")
}

Sample Output

I am inside print function.
After addition of num1 and num2, the result is : 17