Skip to content
Lesson 9 of 19

Step 1 of 5 · Reading · ~3 min

Learn

Functions and Lambdas

Functions

A Kotlin function starts with fun, names its parameters with their types, and declares what it gives back.

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

fun main() {
    println(add(3, 4))
}

//> 7

Parameter types are never optional — the compiler will not guess them. Return types are optional in exactly one situation, which is next.

Two bodies, two rules

FormLooks likeReturn type
Block bodyfun f(x: Int): Int { return x * 2 }required
Expression bodyfun f(x: Int) = x * 2inferred

✓ Expression body — short, and the type is obvious to the compiler:

fun double(x: Int) = x * 2

✗ Block body with the return type left off — this does not compile:

fun double(x: Int) { return x * 2 }

A block body that returns nothing needs no type either. It returns Unit, Kotlin's "no useful value", and by convention you leave it off entirely:

fun shout(text: String) {
    println(text.toUpperCase())
}

Parameters are read-only inside the body. You cannot reassign x in fun f(x: Int); make a local var if you need something that changes.

Default and named arguments

Give a parameter a default and callers may skip it. Name an argument at the call site and the order stops mattering.

fun banner(text: String, width: Int = 10, fill: Char = '-'): String {
    return text.padEnd(width, fill)
}

fun main() {
    println(banner("ok"))
    println(banner("ok", 6))
    println(banner("ok", fill = '.'))
}

//> ok--------
//> ok----
//> ok........

Between them, defaults and named arguments remove nearly all of the overloading you would write in Java. Three overloads of banner collapse into one declaration.

One rule to know: if a parameter with a default comes before one without, callers cannot reach the later one positionally — they have to name it.

fun tag(prefix: String = "[", label: String) = prefix + label

tag(label = "beta")     // fine
// tag("beta")          // error: "beta" binds to prefix, and label is then missing

The easy fix is to put the parameters without defaults first.

vararg — any number of arguments

fun total(vararg values: Int): Int {
    var sum = 0
    for (v in values) sum += v
    return sum
}

fun main() {
    println(total(1, 2, 3))
    println(total())
    val prices = intArrayOf(4, 5)
    println(total(*prices))
}

//> 6
//> 0
//> 9

Inside the function, values is an IntArray. At the call site, * spreads an existing array back out into individual arguments. A function may have only one vararg parameter.

Your exercise

Square It asks you to finish fun square(n: Int): Int so that it returns n * n, and the main you are given prints square of the number read from input.

The starter's body is return 0, a deliberate placeholder. The mistake the grader catches is leaving it in place: add your return n * n above it and every test still prints 0, because the first return reached wins. Replace the line, do not add to it.

Second trap: n^2 is not exponentiation. Kotlin has no ^ operator on numbers at all, so that version does not compile. Write the multiplication out. A hidden test feeds -5 and expects 25, so do not special-case negative input.

Up nextLambdas and Higher-Order FunctionsFunctions and Lambdas

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…