Kotlin Lambda and Higher-Order Functions

A lambda is a function without a name. You create it inline and pass it around like a value. A higher-order function is a function that accepts a function as a parameter, returns a function, or both. Together, these features make Kotlin code concise and expressive.

Lambda Expressions

A regular function has a name and a declaration. A lambda has neither — it is just the logic, written inside curly braces.

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

// Equivalent lambda
val double: (Int) -> Int = { x -> x * 2 }

// Calling both — same result
println(double(5))   // 10

Lambda Syntax Breakdown

{ x: Int, y: Int -> x + y }
  ↑                ↑
  Parameters       Body (expression after ->)

val add: (Int, Int) -> Int = { x, y -> x + y }
// Type annotation: takes two Ints, returns an Int

The it Shortcut

When a lambda has exactly one parameter, you can skip naming it and use it instead.

val square: (Int) -> Int = { it * it }
println(square(6))   // 36

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

Higher-Order Functions

A higher-order function takes another function as a parameter. This lets you write flexible, reusable code.

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

val sum = operate(10, 5) { x, y -> x + y }
val product = operate(10, 5) { x, y -> x * y }

println(sum)      // 15
println(product)  // 50

Diagram — Passing a Lambda

operate(10, 5, { x, y -> x + y })
         │   │      │
         a   b   operation lambda
              │
              └─ called as: operation(10, 5)
                           = 10 + 5 = 15

Trailing Lambda Syntax

When the last parameter of a function is a lambda, Kotlin lets you move it outside the parentheses. This is called trailing lambda syntax and makes call sites look cleaner.

// With lambda inside parentheses:
operate(10, 5, { x, y -> x + y })

// With trailing lambda:
operate(10, 5) { x, y -> x + y }

// If the lambda is the only parameter, drop the parentheses:
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { println(it) }

Built-In Higher-Order Functions

Kotlin's standard library includes many higher-order functions for collections. You will use these constantly in real projects.

map — Transform Each Element

val names = listOf("riya", "arun", "neha")
val upper = names.map { it.capitalize() }
println(upper)   // [Riya, Arun, Neha]

filter — Keep Matching Elements

val scores = listOf(45, 72, 88, 55, 91, 60)
val passing = scores.filter { it >= 60 }
println(passing)   // [72, 88, 91, 60]

reduce — Combine All Elements Into One

val nums = listOf(1, 2, 3, 4, 5)
val total = nums.reduce { acc, n -> acc + n }
println(total)   // 15
// Step: acc=1, n=2 → 3 → acc=3, n=3 → 6 → ... → 15

fold — Like reduce, With a Starting Value

val total = nums.fold(100) { acc, n -> acc + n }
println(total)   // 115  (starts at 100, adds 1+2+3+4+5)

flatMap — Map Then Flatten

val courses = listOf(
    listOf("Kotlin", "Java"),
    listOf("Python", "Swift"),
    listOf("Go")
)
val allCourses = courses.flatMap { it }
println(allCourses)   // [Kotlin, Java, Python, Swift, Go]

Returning Functions from Functions

fun makeMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}

val triple = makeMultiplier(3)
val tenX   = makeMultiplier(10)

println(triple(7))   // 21
println(tenX(5))     // 50

Diagram — Function Factory

makeMultiplier(3)
    │
    └─ returns: { number -> number * 3 }
                        stored as: triple

triple(7) = 7 * 3 = 21

Function Type Reference

You can reference an existing function and pass it as a lambda using the :: operator.

fun isLong(s: String) = s.length > 5

val words = listOf("Hi", "Kotlin", "Go", "Android")
val longWords = words.filter(::isLong)
println(longWords)   // [Kotlin, Android]

Leave a Comment

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