Kotlin Functions
Estimated reading: 4 minutes 62 views

🧬 Kotlin – Lambda Expressions: Write Functions as Values

🧲 Introduction – Why Learn Kotlin Lambda Expressions?

Lambda expressions are anonymous functions—compact, inline chunks of code that can be treated like variables. They’re especially useful in Kotlin for handling callbacks, list operations, event listeners, and more. With Kotlin’s concise syntax, lambdas become a powerful tool for functional and reactive programming.

🎯 In this guide, you’ll learn:

  • What lambda expressions are in Kotlin
  • How to declare and invoke lambdas
  • Use lambdas in higher-order functions like map, filter, forEach
  • Best practices and real-world use cases

⚙️ What Is a Lambda in Kotlin?

A lambda expression is a function that does not have a name and is passed directly as a value.

✅ Basic Syntax:

val greet = { println("Hello from Lambda!") }
greet()

🟢 Output:

Hello from Lambda!

🧾 Lambda with Parameters

val square: (Int) -> Int = { number -> number * number }
println(square(4))  // Output: 16
  • (Int) -> Int = function type: takes an Int, returns an Int
  • { number -> number * number } is the lambda expression

📦 Lambda as Argument to a Function

fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

val result = operateOnNumbers(5, 3) { x, y -> x + y }
println("Sum: $result")

🟢 Output:

Sum: 8

✔️ This is a higher-order function using a lambda as an argument.


🪄 The it Keyword in Single-Parameter Lambdas

When a lambda takes only one argument, you can use it implicitly:

val upperCase: (String) -> String = { it.uppercase() }
println(upperCase("kotlin"))

🟢 Output:

KOTLIN

🔁 Lambdas with Collections – map, filter, forEach

🔹 Using map:

val numbers = listOf(1, 2, 3)
val squares = numbers.map { it * it }
println(squares)

🟢 Output:

[1, 4, 9]

🔹 Using filter:

val evens = numbers.filter { it % 2 == 0 }
println(evens)

🟢 Output:

[2]

🔹 Using forEach:

numbers.forEach { println("Number: $it") }

🔁 Lambda with Return Keyword

val compare: (Int, Int) -> String = { a, b ->
    if (a > b) "A is greater" else "B is greater or equal"
}
println(compare(10, 5))

🟢 Output:

A is greater

🧠 Lambdas vs Anonymous Functions

FeatureLambda ExpressionAnonymous Function
Syntax{ a, b -> a + b }fun(a: Int, b: Int): Int { return a + b }
Return typeInferred automaticallyExplicit return type can be declared
Control flowCannot return from outer functionCan use labeled return to exit outer scope

🚫 Common Mistakes

❌ Mistake✅ Fix
Using return inside lambda in wrong contextUse return@label or avoid if not needed
Misusing it when multiple parametersAlways declare parameters manually
Forgetting function type declarationExplicitly define function type if needed

✅ Best Practices for Kotlin Lambdas

TipWhy It Matters
Use it for single-argument lambdasReduces code clutter
Use named parameters for clarityHelps in multi-parameter lambdas
Prefer lambdas over anonymous functionsLambdas are shorter and more idiomatic
Use trailing lambda syntaxIncreases readability in function calls

📌 Summary – Recap & Next Steps

Kotlin lambda expressions bring concise syntax and functional power to your code. You can treat functions as variables, pass them as arguments, and process collections fluently.

🔍 Key Takeaways:

  • Lambdas are unnamed functions used inline
  • Use it for single-parameter lambdas
  • Lambdas work seamlessly with map, filter, and more
  • Ideal for callbacks and concise logic

⚙️ Practical Use:
Lambdas are crucial in Android click listeners, RxKotlin, collection filtering, coroutines, and functional programming patterns.


❓ FAQs – Kotlin Lambda Expressions

What is a Kotlin lambda expression?
✅ A lambda is an anonymous function used to pass logic as a value.


When should I use it in a lambda?
✅ When there’s only one parameter, Kotlin auto-names it it. For more than one, use explicit names.


Can lambdas return values?
✅ Yes. The last expression in a lambda is its return value:

val square = { x: Int -> x * x }

Can I pass a lambda to a function?
✅ Absolutely. Kotlin supports higher-order functions that accept lambdas as parameters.


What’s the difference between a lambda and an anonymous function?
✅ Lambdas are shorter and inferred, while anonymous functions allow explicit return types and return statements.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Kotlin – Lambda Expressions

Or Copy Link

CONTENTS
Scroll to Top