Chapter 5 of 12 ~14 min read

Functions

How Kotlin functions differ from Java methods — with default params, named args, and single-expression syntax.


Function Syntax

Java
public int add(int a, int b) {
    return a + b;
}

public String greet(String name) {
    return "Hello, " + name + "!";
}

public void printInfo() {
    System.out.println("Info");
}
Kotlin
fun add(a: Int, b: Int): Int {
    return a + b
}

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

// Unit = void (can be omitted)
fun printInfo() {
    println("Info")
}

Single-Expression Functions

When a function body is a single expression, use = — no braces, no return needed:

Java
public int square(int x) {
    return x * x;
}
public boolean isEven(int n) {
    return n % 2 == 0;
}
Kotlin
fun square(x: Int) = x * x
fun isEven(n: Int) = n % 2 == 0

// Return type inferred from expression
fun max(a: Int, b: Int) = if (a > b) a else b

Default Parameter Values

Kotlin default parameters eliminate the overloading chains you write in Java:

Java — overloads
public void createUser(String name) {
    createUser(name, "user", true);
}
public void createUser(
        String name, String role) {
    createUser(name, role, true);
}
public void createUser(
        String name, String role,
        boolean active) { /* impl */ }
Kotlin — one function
fun createUser(
    name: String,
    role: String = "user",
    active: Boolean = true
) { /* impl */ }

createUser("Alice")
createUser("Bob", "admin")
createUser("Carol", active = false)

Named Arguments

Kotlin
fun sendEmail(
    to: String,
    subject: String,
    body: String,
    isHtml: Boolean = false
) { }

// Named args — any order, self-documenting
sendEmail(
    to = "user@example.com",
    body = "Welcome!",
    subject = "Hello",
    isHtml = true
)

Local Functions

Functions inside functions — encapsulate helpers used only in one place:

Kotlin
fun processOrder(items: List<String>) {
    fun validate(item: String) =
        item.isNotBlank() && item.length < 100
    
    val valid = items.filter { validate(it) }
    // process valid...
}

vararg — Variable Arguments

Java
public int sum(int... numbers) {
    int total = 0;
    for (int n : numbers) total += n;
    return total;
}
sum(1, 2, 3);
Kotlin
fun sum(vararg numbers: Int) = numbers.sum()
sum(1, 2, 3)

// Spread an array with *
val arr = intArrayOf(1, 2, 3)
sum(*arr)
Functions Quick Reference
  • fun name(param: Type): ReturnType { } — full syntax
  • fun name(param: Type) = expression — single-expression
  • fun name(param: Type = default) — default parameter
  • fun name(vararg items: Type) — variadic args
  • Unit — return type for void functions (optional to write)