Lambda & Higher-Order Functions

Write concise code with lambdas, pass functions as values, and apply functional programming patterns

{ } -> it HOF

Table of Contents

1Lambda Expressions

A lambda expression is an anonymous function — a function without a name — written inline. Lambdas are the foundation of Kotlin's collection APIs, callbacks, and Compose event handlers.

Basic syntax

Lambda syntax// Full form: { parameters -> body } val sum = { a: Int, b: Int -> a + b } fun main() { println(sum(3, 5)) // 8 val double = { x: Int -> x * 2 } println(double(10)) // 20 }

The implicit it parameter

When a lambda has exactly one parameter, you can omit the parameter name and use it:

it keywordfun main() { val numbers = listOf(1, 2, 3, 4, 5) val squared = numbers.map { it * it } val evens = numbers.filter { it % 2 == 0 } println(squared) // [1, 4, 9, 16, 25] println(evens) // [2, 4] }

Trailing lambda syntax

If the last parameter of a function is a lambda, it can be placed outside the parentheses:

Trailing lambdafun main() { val names = listOf("Kotlin", "Java", "Python") // Equivalent calls: names.forEach({ println(it) }) names.forEach { println(it) } // preferred names.map { name -> name.length } .forEach { println(it) } }

Lambda type notation

Lambda typeMeaning
() -> UnitNo params, no return value
(Int) -> StringOne Int in, String out
(Int, Int) -> IntTwo Ints in, Int out
(String) -> BooleanPredicate — common in filter
Storing lambda in variableval greet: (String) -> String = { name -> "Hello, $name!" } fun main() { println(greet("Nikhil")) }
SAM conversion

For Java functional interfaces or Kotlin fun interface, a lambda can replace the single abstract method — e.g. button.setOnClickListener { ... } in Android.

2Higher Order Functions

A higher-order function (HOF) either takes one or more functions as parameters, returns a function, or both. This enables flexible, reusable code — the pattern behind map, filter, and custom utilities.

Function as parameter

HOF accepting lambdafun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int { return operation(a, b) } fun main() { val add = calculate(10, 5) { x, y -> x + y } val multiply = calculate(10, 5) { x, y -> x * y } println(add) // 15 println(multiply) // 50 }

Function as return value

Returning a functionfun multiplier(factor: Int): (Int) -> Int { return { number -> number * factor } } fun main() { val times3 = multiplier(3) val times5 = multiplier(5) println(times3(10)) // 30 println(times5(10)) // 50 }

Custom higher-order utility

repeat and applyIffun repeat(times: Int, action: (Int) -> Unit) { for (i in 0 until times) { action(i) } } fun <T> List<T>.applyIf( condition: Boolean, transform: (List<T>) -> List<T> ): List<T> { return if (condition) transform(this) else this } fun main() { repeat(3) { i -> println("Iteration $i") } val nums = listOf(1, 2, 3) println(nums.applyIf(true) { it.map { n -> n * 2 } }) }

Standard library HOFs

FunctionLambda roleExample
mapTransform elementlist.map { it * 2 }
filterKeep if truelist.filter { it > 0 }
reduceCombine to one valuelist.reduce { a, b -> a + b }
foldReduce with initiallist.fold(0) { acc, x -> acc + x }
forEachSide effect per itemlist.forEach { println(it) }
let / run / applyScope functionsuser?.let { save(it) }
inline functions: Many stdlib HOFs are inline — the compiler inlines the lambda to reduce overhead. See Inline Functions.

3Anonymous Functions

An anonymous function is another way to pass a function literal — using the fun keyword with a body block. Unlike lambdas, anonymous functions support multiple return points with labeled return.

Anonymous function syntax

Anonymous functionfun main() { val numbers = listOf(1, 2, 3, 4, 5) // Lambda form val evensLambda = numbers.filter { it % 2 == 0 } // Anonymous function form val evensAnon = numbers.filter(fun(n): Boolean { return n % 2 == 0 }) println(evensLambda) // [2, 4] println(evensAnon) // [2, 4] }

Lambda vs anonymous function

FeatureLambdaAnonymous function
Syntax{ x -> x * 2 }fun(x: Int): Int { return x * 2 }
ReturnLast expression is resultreturn exits the function block
Implicit itYes (single param)No — must name parameters
Return typeInferredCan specify explicitly
Typical useShort callbacks, collectionsComplex logic with early return

Non-local return with anonymous function

Early return in anonymous functionfun processNumbers(numbers: List<Int>) { numbers.forEach(fun(n) { if (n < 0) return@forEach // return from anonymous function only println(n) }) } fun main() { processNumbers(listOf(1, -2, 3)) // prints 1, 3 }

When to choose which

Use lambda

Short one-liners: filter { it > 0 }, click listeners, map transforms.

Use anonymous fun

Multi-step logic, explicit return type, or labeled returns from nested HOF.

Labeled return in lambda

In inline HOFs, use return@forEach to return from the lambda only. A bare return in a lambda returns from the enclosing function (non-local return) — only allowed in inline functions.

4Functional Programming Basics

Functional programming (FP) treats computation as evaluation of functions, emphasizes immutability, and avoids changing shared state. Kotlin is multi-paradigm — you can combine OOP with FP patterns.

Core FP concepts in Kotlin

ConceptMeaningKotlin example
First-class functionsFunctions are valuesval f: (Int) -> Int = { it * 2 }
ImmutabilityPrefer unchanging dataval list = listOf(1, 2, 3)
Pure functionsSame input → same output, no side effectsfun add(a: Int, b: Int) = a + b
Higher-order functionsFunctions operating on functionslist.map { it * 2 }
Function compositionCombine small functionsPipeline: filter → map → reduce

Pure vs impure functions

Pure function// Pure — no side effects, predictable fun square(n: Int): Int = n * n // Impure — depends on/modifies external state var counter = 0 fun increment(): Int { counter++ return counter }

Immutable transformation pipeline

FP-style data pipelinedata class Order(val id: Int, val amount: Double, val status: String) fun main() { val orders = listOf( Order(1, 100.0, "PAID"), Order(2, 50.0, "PENDING"), Order(3, 200.0, "PAID") ) val totalPaid = orders .filter { it.status == "PAID" } .map { it.amount } .fold(0.0) { acc, amount -> acc + amount } println("Total paid: $totalPaid") // 300.0 }

Scope functions — functional style helpers

let, run, apply, also, withdata class User(val name: String, var email: String) fun main() { val user = User("Nikhil", "old@mail.com") user.apply { email = "new@mail.com" } val display = user.let { u -> "${u.name} <${u.email}>" } println(display) }
Scope functionObject refReturn valueTypical use
letitLambda resultNull-safe transform
runthisLambda resultConfigure + compute
applythisObject itselfObject initialization
alsoitObject itselfSide effects / logging
withthisLambda resultGroup calls on object

FP benefits in Android & backend

Fewer bugs

Immutable data and pure functions reduce race conditions and unexpected mutations.

Composable logic

Small functions chain into readable pipelines — filter, map, reduce.

Testability

Pure functions are easy to unit test — no mocks for global state.

Modern Android

Compose, Flow, and coroutines embrace functional reactive patterns.

Practical balance: Kotlin does not require pure FP — use immutable collections and HOFs where they simplify code, and OOP where it models domain entities. Related: Collections, Coroutines.

5Summary Cheatsheet

TopicKey Takeaway
Lambda Expressions{ params -> body }; it for single param; trailing lambda
Higher-Order FunctionsTake/return functions; map, filter, custom utilities
Anonymous Functionsfun(x): T { return ... }; explicit return, labeled return
Functional ProgrammingImmutability, pure functions, pipelines, scope functions
Lambda type(Int, Int) -> Int — parameters and return type
Next lessonGenerics — type parameters and reified types

Lambda & Higher-Order Functions MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Lambda & Higher-Order Functions MCQs

1

Lambda syntax in Kotlin?

Alambda x:
B{ x -> body }
Cfn(x)
Dx => body
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
2

Single parameter lambda can use?

Ait as implicit name
BOnly full name
CNo parameters ever
D_ only
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
3

Higher-order function?

AReturns only Int
BTakes or returns a function
CStatic only
DInline only
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
4

Trailing lambda convention?

ALambda outside last parentheses
BLambda must be first param
CNo lambdas in Kotlin
DJava only
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
5

filter { it > 0 } — it is?

AGlobal variable
BImplicit name for single lambda param
CKeyword
DReturn type
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
6

Labeled return from lambda?

Areturn only
Breturn@label to exit specific lambda
Cbreak@lambda
DNot allowed ever
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
7

Anonymous function syntax?

Afun(x: Int): Int { return x * 2 }
Blambda only allowed
Cdef(x)
Dfunction(x)
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
8

Function type notation?

A(Int) -> String
BInt:String
CFunc
Dlambda
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
9

SAM conversion applies to?

AAny class
BFunctional interface with one abstract method
CData class
DSealed class
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
10

stdlib filter is?

Ainline higher-order function
BJava only
CNot a function
DMacro
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.

10 Advanced Lambda & Higher-Order Functions MCQs

11

also scope function returns?

ALambda result
BThe object itself (receiver)
Cnull
DBoolean only
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
12

apply vs let?

ASame always
Bapply returns receiver; let returns lambda result
Clet returns receiver
Dapply returns null
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
13

Closure in Kotlin?

ANot supported
BLambda can capture variables from enclosing scope
COnly globals
DOnly vals
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
14

Sequence vs List chain?

ASequence eager
BSequence lazy — computes on demand
CSame
DSequence mutable
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
15

fold needs?

AInitial accumulator value
BNo parameters
COnly strings
DInline only
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
16

takeWhile?

ATakes elements while predicate true then stops
BSorts list
CRemoves all
DMaps only
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
17

any vs all?

Aany: at least one matches; all: every element matches
BSame
Cany for maps only
Dall throws
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
18

run scope function?

ARuns block on receiver; returns lambda result
BOnly for threads
CCreates copy
DInline only macro
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
19

noinline on lambda param?

AForce inline
BDo not inline that lambda
CMake reified
DDelete lambda
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is B.
20

Higher-order function benefit?

AMore boilerplate
BPass behavior as data — flexible APIs
CSlower always
DJava incompatible
Explanation: See Lambda & Higher-Order Functions lesson — correct answer is A.
Click an option to select, then check answers.

Lambda & Higher-Order Functions Interview Q&A

15 topic-focused questions for interviews and revision.

1What is a lambda in Kotlin?easy
Answer: Anonymous function: { params -> body } or { it -> body } for single param. Can be passed as value.
2What is a higher-order function?easy
Answer: Function that takes another function as parameter or returns a function — e.g. list.filter { }.
3What is trailing lambda syntax?easy
Answer: If last parameter is lambda, place it outside parens: repeat(3) { println(it) }.
4When use it in lambdas?easy
Answer: When lambda has single parameter and you do not declare name — list.map { it * 2 }.
5Difference between lambda and anonymous function?medium
Answer: Lambda: concise, return inferred. Anonymous fun: explicit return type, return allowed without label in some cases.
6What is a function type?medium
Answer: (Int, Int) -> Int represents function taking two Ints and returning Int — can be stored in variables.
7Explain SAM conversion.medium
Answer: Lambda can replace functional interface with single abstract method — e.g. Runnable { } in Java interop or fun interface.
8Why inline higher-order functions?medium
Answer: Avoids object allocation for lambdas; enables reified generics and non-local returns in some cases.
9Scope functions: let vs apply vs also?medium
Answer: let: it, returns result. apply: this, returns receiver. also: this, returns receiver after side effect. run/with: block on receiver.
10Labeled return in lambda?medium
Answer: return@filter exits only the lambda passed to filter, not enclosing function — required in inline HOFs.
11When use Sequence?hard
Answer: Long chain on large collection — lazy evaluation avoids intermediate lists from multiple map/filter calls.
12noinline vs crossinline?hard
Answer: noinline: keep lambda as object. crossinline: inline but forbid non-local return from that lambda.
13Capturing mutable var in lambda?hard
Answer: Lambda captures variable reference — changes visible inside lambda; be careful with concurrency.
14Custom higher-order function example?hard
Answer: fun repeat(n: Int, action: (Int) -> Unit) { for (i in 0 until n) action(i) } — passes behavior as parameter.
15Functional programming benefits in Kotlin?hard
Answer: Immutable transformations, declarative collection ops, less mutable state — composable filter/map/reduce pipelines.