CodeGym /행동 /Kotlin SELF /Kotlin lambda expressions: syntax, it, return value

Kotlin lambda expressions: syntax, it, return value

Kotlin SELF
레벨 21, 레슨 0
사용 가능

1. Lambda functions: getting acquainted

If you are still not very confident with programming, lambdas can sound like “some kind of functional-programming magic”. In reality, the idea is very down-to-earth: sometimes we want to treat an action the same way we treat a number or a string. A number can be put into a variable, passed into a function, returned from a function. With a lambda we do the same thing—except we store not data, but a small piece of logic.

Imagine that in our console expense tracker, in one place we want to consider an amount from 1000 as a “big expense”, and in another—from 500. If the rule is hard-coded in an if, you will have to copy if (amount >= 1000) all over the project and then heroically search for the place you forgot to update. A lambda lets you write the “rule” once, assign it to a variable, and use it where needed.

2. Lambda as a value: store in val and call it

The most important thing to internalize hands-on: a lambda is not a “special operator”, but a value. That means you can actually store it in a variable. And since it’s a value, you can then “call” it like a regular function.

Let’s start with the simplest possible example: checking if a number is even.

fun main() {
    val isEven: (Int) -> Boolean = { x -> x % 2 == 0 }

    println(isEven(4))  // true
    println(isEven(5))  // false
}

Several useful things happen here at once.

First, on the right side of = we created a lambda { x -> x % 2 == 0 }.

Second, on the left we honestly specified the variable type: (Int) -> Boolean. Don’t dive too deep yet—just think of it as a “function type”. It literally says: “takes an Int, returns a Boolean”.

Third, below we call the lambda the same way as a function: isEven(4). So the variable isEven behaves like a function.

To reinforce the idea “lambda is a value”, here is another example where a lambda returns a string:

fun main() {
    val greet: (String) -> String = { name -> "Hello, $name!" }

    println(greet("Kotlin"))  // Hello, Kotlin!
}

Same idea: we store the “greeting formula” in a variable and can call it as many times as we want.

Create vs call: different actions

Even in this first lecture it is useful to build one habit: distinguish the place where you create a lambda from the place where you call it.

Compare:

fun main() {
    val inc: (Int) -> Int = { it + 1 }  // create and store

    val a = inc(10)                      // call
    println(a)                           // 11
}

If you wrote { it + 1 } but never wrote inc(10) anywhere, nothing will happen. A lambda does not “run by itself”; it is not a background daemon and not a timer.

3. Lambda syntax and the it parameter

Basic form: { parameters -> body }

It’s easy to get confused with lambdas because there are braces, an arrow, and a feeling that you accidentally opened a portal to another dimension. Let’s tame it as ordinary language grammar: “here are the parameters, here is the body, here is what gets returned”.

The basic form of a Kotlin lambda looks like this: always curly braces, inside parameters, then the arrow ->, then the body. Parameters (with optional types) go before ->, the body after it, and the return value is taken from the last expression.

Here is a mini table of “how to read it”:

Fragment What it means Example
{ ... }
“This is a lambda” (always in braces)
{ x -> x + 1 }
x to the left of -> lambda parameter
{ x -> ... }
->
“from parameters to body”
{ x -> x + 1 }
expressions on the right lambda body
{ x -> x + 1 }

And here is an example a bit longer, but still simple:

fun main() {
    val addVat: (Int) -> Int = { price ->
        price + (price * 20 / 100)
    }

    println(addVat(100))  // 120
    println(addVat(250))  // 300
}

Here the parameter is named price, the body is the expression price + ..., and the lambda result will be the value of the last expression.

Notice an important reading habit: when you see { ... -> ... }, mentally replace it with “a small function without a name”. Not a “magic block”, not a “special list syntax”, but a function.

One parameter: you can use it

When a lambda has exactly one parameter, Kotlin often allows you not to declare it explicitly. Then the parameter is automatically available under the name it. If the signature is clear from context and there is only one parameter, you can omit the name and the compiler will provide it.

Example: checking “is the number positive?”:

fun main() {
    val isPositive: (Int) -> Boolean = { it > 0 }

    println(isPositive(10))  // true
    println(isPositive(-1))  // false
}

Here it is that one and only Int passed into the lambda.

It’s important not to turn it into a religion. it is good when the condition is short and obvious. If the logic is more complex, it’s better to name the parameter meaningfully—otherwise you will read the code like a riddle: “and it is what… a number? a string? a cat?”.

Compare two variants:

fun main() {
    val ok1: (String) -> Boolean = { it.trim().isNotEmpty() }
    val ok2: (String) -> Boolean = { text -> text.trim().isNotEmpty() }

    println(ok1("   "))  // false
    println(ok2("hi"))   // true
}

Both variants are correct. The second sometimes reads more calmly, especially if you later add a couple more lines to the lambda body.

4. Return value and multi-line lambdas

What a lambda returns: the result of the last expression

Kotlin lambdas have a very convenient convention: if you don’t explicitly write return@..., then the lambda value is the last expression in its body.

Let’s look at an example. We want a string description of a number:

fun main() {
    val describe: (Int) -> String = { n ->
        val sign = if (n >= 0) "non-negative" else "negative"
        "n=$n ($sign)"
    }

    println(describe(7))    // n=7 (non-negative)
    println(describe(-3))   // n=-3 (negative)
}

The last line inside the lambda is the string "n=$n ($sign)". So that’s exactly what becomes the result of the lambda.

A very practical check: “what does the lambda end with?” If it ends with println(...), then the result will be Unit (because println returns Unit). If it ends with an expression that evaluates to a value, then the lambda will return that value.

Here is an example of a “lambda that performs an action” (and returns Unit):

fun main() {
    val log: (String) -> Unit = { msg ->
        println("LOG: $msg")
    }

    log("Starting!")  // LOG: Starting!
}

In learning tasks, a common confusion is: “I thought that since the lambda is written, it will already do something.” No—until you call it, it just sits in a variable, like a borscht recipe. The recipe doesn’t cook the borscht by itself.

Multi-line lambda: like a small function

When you first see a 5–6 line lambda, your brain may start panicking: “why is a function without a name living inside braces, is this even legal?”. It is. And it can be useful—if you do it carefully.

A multi-line lambda reads like a regular function: inside you can declare intermediate val, you can use if as an expression, and at the end return the final result.

For example, let’s make a lambda that formats a money amount for output (roughly: mark big amounts with "(!)"):

fun main() {
    val formatAmount: (Int) -> String = { amount ->
        val badge = if (amount >= 1000) " (!)" else ""
        "$amount$badge"
    }

    println(formatAmount(120))    // 120
    println(formatAmount(1500))   // 1500 (!)
}

Notice the style: we don’t try to cram everything into one line, but we also don’t turn the lambda into a “three-volume novel”. Inside there is one intermediate val, and the last line is the final result.

If we want to get a bit “closer to reality”, let’s take an element from our practical app. For now, we store an expense as Triple(id, category, amount) (without classes—because we’ll get to OOP later).

fun main() {
    val formatExpense: (Triple<Int, String, Int>) -> String = { exp ->
        val (id, category, amount) = exp
        val mark = if (amount >= 1000) " (!)" else ""
        "#$id $category: $amount$mark"
    }

    println(formatExpense(Triple(1, "food", 450)))     // #1 food: 450
    println(formatExpense(Triple(2, "rent", 15000)))   // #2 rent: 15000 (!)
}

Technically this is still “just a lambda”, but it feels like a small formatting function that you can reuse in different places without copying string templates.

5. Types in lambdas: where Kotlin can infer them

Up to this point we honestly wrote the variable type on the left: (Int) -> Boolean, (String) -> String, and so on. But Kotlin can often infer the type by itself—either from parameter types or from context.

The simplest example: the parameter type is specified right in the lambda, so the type of the whole lambda is clear:

fun main() {
    val square = { x: Int -> x * x }

    println(square(5))  // 25
}

Here the type of the variable square is inferred automatically: since the parameter is Int and the result is Int, it’s something like a function Int -> Int.

And here is an example where Kotlin cannot infer it because you wrote it too “abstractly”:

fun main() {
    // Don't do this: the compiler has nowhere to learn the type of x
    // val id = { x -> x }

    val idInt: (Int) -> Int = { x -> x }
    println(idInt(42))  // 42
}

Why is the first version bad? Because x has no type, there is no context, and the compiler cannot read minds. In such cases you either specify the parameter type directly in the lambda ({ x: Int -> x }) or specify the variable type on the left (val idInt: (Int) -> Int = ...).

6. Mini example: “rule” and formatting as lambdas

Let’s take a small but practical step toward “real” code. We won’t build complex abstractions yet—we’ll just show that logic can be put into variables: separately “how to print”, separately “what counts as big”.

Imagine that somewhere in our app we want to print a list of expenses, but mark large amounts. Let’s make two lambdas: isBig and format.

fun main() {
    val expenses = listOf(
        Triple(1, "food", 450),
        Triple(2, "transport", 120),
        Triple(3, "rent", 15000)
    )

    val isBig: (Int) -> Boolean = { it >= 1000 }
    val format: (Triple<Int, String, Int>) -> String = { exp ->
        val (id, category, amount) = exp
        val mark = if (isBig(amount)) " (!) " else " "
        "#$id$mark$category: $amount"
    }

    for (e in expenses) {
        println(format(e))
        // #1 food: 450
        // #2 transport: 120
        // #3 (!) rent: 15000
    }
}

The nice thing here is that if tomorrow you decide that “big” starts at 5000, you change one place: val isBig = { it >= 5000 }. And formatting will automatically use the new rule—because format calls isBig(amount) inside.

This is not yet “passing behavior into functions” (we’ll get to that a bit later), but it is already a good transition from “everything is hard-coded in if” to a cleaner structure.

7. Common mistakes when working with lambda expressions

Mistake #1: using it when there is more than one parameter.
it exists only for a lambda with one parameter. If there are two parameters, you must write { a, b -> ... }. If you try to “force” it into it, the code either won’t compile or will become unreadable, because you will start inventing odd names and confusing what goes where.

Mistake #2: expecting the lambda to execute by itself just because it’s written.
A lambda is a value. It doesn’t start running at the moment of declaration. Until you call it via f(x) (or pass it somewhere that will call it), it just sits in a variable. A very typical symptom: “I wrote { println("hi") }, but it prints nothing”.

Mistake #3: forgetting that the last expression is returned, and accidentally returning Unit.
When the lambda ends with println(...), the lambda effectively returns Unit. Sometimes that is surprising because you “seem to have computed a value”, but then you printed in the last line. The fix is simple: make the computation the last expression (and printing a separate step), or store the computation in a val and return it as the last line. The rule “the last expression becomes the result” is fundamental.

Mistake #4: writing a lambda that is too large inline and losing the meaning.
If your lambda is 15 lines long, has three ifs, two counters, and a bit of philosophy—your brain will struggle. Even if it works formally, reading such code is unpleasant. In such cases it is usually better either to give the parameter a meaningful name (instead of always it), or extract the logic into a separate named function and keep the lambda short and clear.

Mistake #5: leaving types with zero hints and getting Cannot infer a type for this parameter.
A lambda like { x -> x } looks reasonable to a human, but the compiler is not obligated to guess what you meant. If the context doesn’t provide the type, Kotlin will ask you to clarify: either x: Int or the variable type on the left. This is normal: the compiler is not being picky—it just requires unambiguity so that it doesn’t have to guess which version of the code to run.

1
과제
Kotlin SELF, 레벨 21, 레슨 0
잠금
하나 더하기
하나 더하기
1
과제
Kotlin SELF, 레벨 21, 레슨 0
잠금
이름으로 인사하기
이름으로 인사하기
1
과제
Kotlin SELF, 레벨 21, 레슨 0
잠금
계산대 할인
계산대 할인
1
과제
Kotlin SELF, 레벨 21, 레슨 0
잠금
더 길거나 같음
더 길거나 같음
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION