Phase 1 · FoundationsModule 6~34 min read

Functions

Declare expressive functions with default and named arguments, single-expression bodies, and varargs.

What you'll learn

Functions are how you break a program into small, named, reusable pieces. Kotlin's functions are especially expressive — with default and named arguments, and a concise single-expression form.

By the end you'll be able to:

  • Declare functions with fun, parameters, and return types
  • Use default and named arguments
  • Write concise single-expression functions
  • Accept any number of arguments with vararg
  • Write local and recursive functions

Defining functions

A function starts with fun, then its name, parameters (each with a name: Type), and an optional return type after a colon. A function that returns nothing has the return type Unit, which you normally just omit:

Anatomy of a function
fun add(a: Int, b: Int): Int {
    return a + b
}
■

fun — the keyword that declares a function.

■

Name — in camelCase, describing what it does.

■

Parameters — each with a name and type.

■

Return type — after the colon (omit for Unit).

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

fun printSum(a: Int, b: Int) {     // no return type = Unit (nothing)
    println(a + b)
}

println(greet("Sara"))
printSum(2, 3)

Default & named arguments

Kotlin parameters can have default values, so callers can omit them. And you can pass arguments by name, in any order — which makes calls self-documenting and removes the need for the many overloaded methods you'd write in Java:

Arguments.kt
fun greet(name: String, greeting: String = "Hello"): String {
    return "$greeting, $name!"
}

println(greet("Sara"))                          // Hello, Sara!
println(greet("Omar", "Welcome"))               // Welcome, Omar!
println(greet(greeting = "Hi", name = "Aisha")) // named args, any order

Tip

Default + named arguments are a big deal. Where Java needs five overloaded constructors for optional parameters, Kotlin needs one function with defaults. Name your arguments whenever it makes a call clearer.

Single-expression functions

When a function's body is just a single expression, drop the braces and return and use an = instead. The return type is inferred. It's perfect for short, focused functions:

Single.kt
// when a function is just one expression, use = (no braces, no return)
fun square(n: Int) = n * n
fun max(a: Int, b: Int) = if (a > b) a else b

println(square(5))    // 25
println(max(3, 7))    // 7

Varargs

Mark a parameter vararg and the function accepts any number of arguments, available inside as an array:

Varargs.kt
fun sum(vararg numbers: Int): Int {
    var total = 0
    for (n in numbers) total += n
    return total
}

println(sum(1, 2, 3))        // 6
println(sum(10, 20, 30, 40)) // 100

Local & recursive functions

A function can call itself — recursion — as long as it has a base case that stops it. And Kotlin lets you define local functions inside other functions, handy for helpers that aren't needed elsewhere:

Recursion.kt
fun factorial(n: Int): Int =
    if (n <= 1) 1 else n * factorial(n - 1)

println(factorial(5))   // 5 * 4 * 3 * 2 * 1

Note

For deep recursion, mark a function tailrec and Kotlin optimises it into a loop, avoiding a stack overflow — provided the recursive call is the very last thing the function does.

Recap & quick check

Key takeaways

  • Declare functions with fun name(params): ReturnType; omit the type for Unit (returns nothing).
  • Parameters can have default values, and arguments can be passed by name in any order.
  • Single-expression functions use = instead of braces and return (the type is inferred).
  • vararg accepts any number of arguments as an array.
  • Functions can recurse (with a base case) and be defined locally; tailrec optimises tail recursion.

Quick check

1. What keyword declares a function in Kotlin?

2. What is the return type of a function that returns nothing?

3. What do default arguments let you avoid?

4. How do you write a single-expression function?

5. What does 'vararg' do?

Superb. Next up: Module 7 — Strings & Console I/O, the finale of Phase 1.