CodeGym /Courses /Kotlin SELF /Expression body and local functions

Expression body and local functions

Kotlin SELF
Level 8, Lesson 4
Available

1. A function as an expression

When you start actively extracting code into functions, a typical story happens: the file becomes nicer, main() gets shorter, but… you end up with lots of functions. And among them you’ll find ones that are logically sound, but in size look like “5 lines for one thought.” Too many tiny functions can be inconvenient.

On the other hand, if you keep everything in a single main, you get a “wall of text.” So we need balance: small functions are good, but code-for-the-sake-of-code can get in the way. In Kotlin we have two tools to maintain that balance: expression body (a short function body via =) and local functions (functions inside other functions).

Expression body

Expression body is a way to tell Kotlin: “this function’s body is a single expression, let’s write it nicely—without braces and without return.” Suppose we need a function to square a number. Here’s the classic form:

fun square(x: Int): Int {
    return x * x
}

But we can write it shorter:

fun square(x: Int): Int = x * x

Same meaning, but the notation is closer to a mathematical formula. For simple calculations and checks, this often reads better: the function looks like a definition, not a mini script.

Mini example 1: computing x cubed

fun cube(x: Int): Int = x * x * x

fun main() {
    println(cube(3)) // 27
}

Mini example 2: checking for even

fun isEven(x: Int): Boolean = x % 2 == 0

fun main() {
    println(isEven(10)) // true
    println(isEven(7))  // false
}

What matters here is the core idea: isEven reads like a question, and on the right is the “answer formula.” For beginners, honestly, this is one of the most pleasant ways to read code.

2. Expression body: type inference and when a block body is better

Expression body has a nice bonus: Kotlin can often infer the return type from the expression on the right. That means you can write it even shorter:

fun square(x: Int) = x * x

And the compiler will infer the type as Int.

But you need to be careful: sometimes an explicit type is not “extra typing,” but consideration for the reader. So let’s agree on a simple rule: if the function is completely obvious, you can omit the type; if there is even a hint of doubt, it’s better to keep it.

Let’s compare in a table:

Option Example When to use
Expression body + explicit type
fun isEven(x: Int): Boolean = x % 2 == 0
When you want the contract to be readable immediately
Expression body + type inference
fun isEven(x: Int) = x % 2 == 0
When the expression is максимально obvious
Block body
fun f(...) { ... }
When there are multiple steps, if, a loop, variables

Mini example: a string as the result

fun formatMoney(amount: Int): String = "$amount €"

fun main() {
    println(formatMoney(120)) // 120 €
}

When it’s better not to use expression body

Expression body has a trap: if it can be shorter, it must be shorter. As a result, the code turns into one-line monsters where half the logic is hidden in parentheses, and you only want to read it under threat of a deadline.

If a function contains multiple steps, intermediate variables, a loop, or branching, then a block body is usually more logical: it shows that this is not a formula, but a process.

Compare the feel. This is fine and readable:

fun absInt(x: Int): Int {
    if (x < 0) return -x
    return x
}

This is already questionable for a beginner (though technically correct):

fun absInt(x: Int): Int = if (x < 0) -x else x

4. Mini app: “Expense jar”

So we don’t discuss compactness in a vacuum, let’s keep developing a single console app. Let it be a simple “expense jar”: the user enters several expenses (amounts), and the program computes the total, the maximum, and the average.

First we’ll sketch a simple skeleton (as if it already existed in previous lectures), and then we’ll start “tidying it up.”

fun main() {
    val amounts = intArrayOf(120, 80, 200, 50)

    val total = sumAmounts(amounts)
    val max = maxAmount(amounts)
    val avg = averageAmount(amounts)

    println("Итого: $total")     // Итого: 450
    println("Максимум: $max")    // Максимум: 200
    println("Среднее: $avg")     // Среднее: 112.5
}

For now we’ll implement the functions in the usual way, so we have something to work with:

fun sumAmounts(xs: IntArray): Int {
    var total = 0
    for (x in xs) {
        total += x
    }
    return total
}

fun maxAmount(xs: IntArray): Int {
    var m = xs[0]
    for (x in xs) {
        if (x > m) m = x
    }
    return m
}

fun averageAmount(xs: IntArray): Double {
    val total = sumAmounts(xs)
    return total.toDouble() / xs.size
}

Now let’s look with “code editor” eyes: which functions here are candidates for expression body? averageAmount—yes, because its logic is almost formula-like (even though there’s an intermediate variable). We can make it a bit more compact, but without fanaticism.

A neat option, still readable:

fun averageAmount(xs: IntArray): Double = sumAmounts(xs).toDouble() / xs.size

And here you can clearly see the main benefit: we didn’t “compress code for the sake of compression,” we made the function look like a definition of the average.

Let’s update the whole example (note: we kept sumAmounts and maxAmount as block bodies because there’s a loop there—and that’s no longer “one expression”):

fun averageAmount(xs: IntArray): Double = sumAmounts(xs).toDouble() / xs.size

fun main() {
    val amounts = intArrayOf(120, 80, 200, 50)
    println(averageAmount(amounts)) // 112.5
}

5. Local functions in the app

Sometimes you need a function only as a small helper inside a single scenario. Pulling it up to the file level means “cluttering the namespace”: you get one more name, one more thing you can accidentally use where you shouldn’t. A local function solves this: you declare fun helper(...) прямо inside another function, and it exists only there.

This is similar to how you create a local variable: you don’t declare every temporary variable globally across the whole file. Local functions follow the same idea: “it lives next to where it’s used and doesn’t interfere with the rest.”

An important point: a local function can access variables of the outer function and even modify them (i.e., use the “outer environment”). This behavior is the same as with other nested constructs that can capture variables from an outer scope.

Input with parsing and validation

Let’s take the next step in the “expense jar”: instead of a hard-coded array, we’ll read expenses from the console. But that immediately gives us a typical input scenario: read a string, trim whitespace, parse a number, check that it’s positive. And this scenario often ends up either duplicated or too long inside main.

Let’s make a function readPositiveInt(prompt: String): Int, and inside it we’ll hide local helpers.

fun readPositiveInt(prompt: String): Int {
    fun parseIntOrNull(text: String): Int? {
        val cleaned = text.trim()
        return cleaned.toIntOrNull()
    }

    while (true) {
        print(prompt)
        val raw = readln()
        val value = parseIntOrNull(raw)

        if (value != null && value > 0) return value
        println("Введите целое число больше 0.")
    }
}

Here the local function parseIntOrNull isn’t needed by the whole program—it’s only needed for this input. So keeping it inside is logical: you read readPositiveInt, and you immediately see how exactly we parse the string.

A small flowchart of the input process

flowchart TD
    A[Показать prompt] --> B[Прочитать строку]
    B --> C[trim]
    C --> D[toIntOrNull]
    D --> E{value != null и value > 0?}
    E -- да --> F[return value]
    E -- нет --> G[Сообщение об ошибке]
    G --> A

Now we’ll use this function in main and build a fixed-size expenses array. We’ll ask the user for the size as well—this will feel closer to a real program.

fun main() {
    val n = readPositiveInt("Сколько расходов ввести? ")

    val amounts = IntArray(n)
    for (i in 0 until n) {
        amounts[i] = readPositiveInt("Расход #${i + 1}: ")
    }

    println("Итого: ${sumAmounts(amounts)}") // например: Итого: 450
}

Combining approaches: helpers and expression body

The most enjoyable part starts when you combine the tools. Local functions help hide one-off details, and expression body makes “formula-like” functions short and readable.

For example, in our app we can make a small amount-formatting function, and it’s a perfect fit for expression body. And this is useful even now, when it feels like “I can just write $amount € directly in println.” You can—but later you’ll want to change the format (for example, add the word “euro”), and you’ll end up searching the file for every place you printed the amount.

fun formatMoneyEuro(amount: Int): String = "$amount €"

And inside main:

fun main() {
    val amounts = intArrayOf(120, 80, 200, 50)
    val total = sumAmounts(amounts)

    println("Итого: ${formatMoneyEuro(total)}") // Итого: 450 €
}

Another good candidate is the “average,” which we already did:

fun averageAmount(xs: IntArray): Double = sumAmounts(xs).toDouble() / xs.size

Now let’s improve the final output a bit, but carefully: no huge formatting and no new topics.

fun printReport(amounts: IntArray) {
    val total = sumAmounts(amounts)
    val max = maxAmount(amounts)
    val avg = averageAmount(amounts)

    println("Итого: ${formatMoneyEuro(total)}")     // Итого: 450 €
    println("Максимум: ${formatMoneyEuro(max)}")    // Максимум: 200 €
    println("Среднее: $avg")                       // Среднее: 112.5
}

And main becomes a “script,” not a “bag of logic”:

fun main() {
    val n = readPositiveInt("Сколько расходов ввести? ")

    val amounts = IntArray(n)
    for (i in 0 until n) {
        amounts[i] = readPositiveInt("Расход #${i + 1}: ")
    }

    printReport(amounts)
}

This is exactly where you can see why all of this matters: main reads like a sequence of steps, while details are split into functions. At the same time, we don’t breed extra “one-off” functions at the file level: what’s needed only inside input stays local.

6. Common mistakes with expression body and local functions

Mistake #1: turning expression body into a “brain compressor.”
Sometimes you want to pack everything into =, including complex conditions and multi-level computations. Formally the compiler will swallow it, but a human won’t always. If the line stops being readable “at a glance,” it’s better to go back to a block body and honestly spell out the steps.

Mistake #2: trying to use expression body where a loop or multiple actions are needed.
Expression body is about a single expression. If you have a for, accumulating a sum, updating a variable, printing intermediate values—that’s already a script, and a regular { ... } fits it better. Don’t think of a block body as “worse”: it’s just for a different kind of task.

Mistake #3: pulling out functions that are needed in exactly one place.
Often a beginner makes a dozen tiny helper functions at the file level, and then gets confused about which one is used where. A local function is a good compromise: it gives a step a name, but doesn’t bloat the file’s external API. If a helper is used only inside a single input function—let it live there.

Mistake #4: overcomplicating local functions and hiding important logic too deep.
A local function should be small and to the point. If inside readPositiveInt you declared 5 local functions, and each is 20 lines long, that’s no longer “hid details,” it’s “made a quest.” In that case it’s better to move part of it to the file level and give it a proper name.

Mistake #5: accidentally relying on outer variables and getting unexpected effects.
Local functions can access and modify variables of the outer function—that’s convenient, but can become a trap if you didn’t notice that a helper changes state. Keep such changes obvious: if a helper changes something, that should be readable from the code, not a surprise.

1
Task
Kotlin SELF, level 8, lesson 4
Locked
Warm-up timer
Warm-up timer
1
Task
Kotlin SELF, level 8, lesson 4
Locked
Name on the badge
Name on the badge
1
Task
Kotlin SELF, level 8, lesson 4
Locked
Safe limit
Safe limit
1
Task
Kotlin SELF, level 8, lesson 4
Locked
Robust input
Robust input
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION