Kotlin Lambda Expressions

Kotlin Lambda Expressions (Deep Explanation)

In Kotlin, lambda expressions are anonymous functions (functions without a name). They are widely used in higher-order functions, collections, and functional programming.


1. What is a Lambda Expression?

A lambda expression is a block of code that can be assigned to a variable or passed as a parameter.

Syntax

{ parameters -> body }

2. Basic Lambda Example

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

greet("Kotlin")


3. Lambda with Return Value

The last expression is automatically returned.

val sum = { a: Int, b: Int ->
a + b
}

println(sum(3, 5)) // 8


4. Lambda Type Declaration

You can explicitly define the lambda type.

val multiply: (Int, Int) -> Int = { a, b ->
a * b
}

5. it Keyword (Single Parameter)

If a lambda has only one parameter, Kotlin uses it.

val square: (Int) -> Int = {
it * it
}

println(square(4)) // 16


6. Lambda as Function Parameter

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

fun main() {
val result = calculate(10, 5) { x, y ->
x + y
}
println(result)
}


7. Trailing Lambda Syntax (Very Important)

If the last parameter is a function, write lambda outside parentheses.

fun show(action: () -> Unit) {
action()
}

show {
println("Hello from lambda")
}


8. Lambda with Multiple Statements

val process = { x: Int ->
val y = x * 2
println(y)
y + 1
}

println(process(5))


9. Lambdas in Collections (Real Usage)

map

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

filter

val even = nums.filter { it % 2 == 0 }
println(even)

reduce

val sum = nums.reduce { acc, i -> acc + i }
println(sum)

10. Lambda with Receiver

Used in scope functions and DSLs.

val result = StringBuilder().apply {
append("Hello ")
append("Kotlin")
}.toString()

println(result)

Here, this refers to StringBuilder.


11. Anonymous Function vs Lambda

Lambda

val add = { a: Int, b: Int -> a + b }

Anonymous Function

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

Anonymous functions allow explicit return statements.


12. return in Lambda (Important Rule)

❌ This is invalid:

// return is not allowed like this

✔ Use labels:

nums.forEach {
if (it == 2) return@forEach
println(it)
}

13. Inline Lambdas (Performance)

inline fun execute(action: () -> Unit) {
action()
}

Reduces overhead of lambda objects.


Summary

  • Lambdas are anonymous functions

  • Last expression is returned

  • it for single parameter

  • Widely used with collections and HOFs

  • Core concept in modern Kotlin

You may also like...