Defining and Calling Functions

Function Syntax

A function is a named block of code you can call many times. It is declared with fun, then the name, the parameters with their types, and the return type after a colon.

fun  name(param1: Type, param2: Type): ReturnType {
    ...
    return value
}

Example

Parameters always need a type. The return type comes after the parameter list.

fun greet(name: String) {
    println("Hello, $name!")
}

fun add(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    greet("Asha")
    greet("Ravi")
    val sum = add(7, 8)
    println("Sum: $sum")
    println("Nested call: ${add(add(1, 2), 3)}")
}

Output

Hello, Asha!
Hello, Ravi!
Sum: 15
Nested call: 6

Top-level Functions vs Java

Kotlin functions can live directly in a file, outside any class. In Java every method must be inside a class (often a static method in a Utils class).

// Java
public class PriceUtils {
    public static int applyDiscount(int price, int percent) {
        return price - price * percent / 100;
    }
}
int p = PriceUtils.applyDiscount(500, 10);
// Kotlin: PriceUtils.kt
fun applyDiscount(price: Int, percent: Int): Int = price - price * percent / 100

val p = applyDiscount(500, 10)

Parameters are Read-Only

fun double(x: Int): Int {
    x = x * 2      // ERROR: Val cannot be reassigned (parameters are val)
    return x
}

Tip: Create a local val if you need a modified copy: val doubled = x * 2.