Skip to main content
Kotlin Basics
CHAPTER 19 Beginner

Lambdas and Functional Programming

Updated: May 18, 2026
5 min read

# CHAPTER 19

Lambdas and Functional Programming

1. Chapter Introduction

In Chapter 18, we learned that we can pass functions into other functions. However, defining a full fun sum(a: Int, b: Int) just to use it once as a parameter is excessive. This is where Lambdas come in. Lambdas are anonymous functions (functions without a name) that you can write directly inline. In this chapter, we will master Lambdas and use them to process Collections with functional operations like map and filter.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Write Lambda expressions using { }.
  • Understand the it keyword.
  • Use Trailing Lambda syntax.
  • Transform lists using map.
  • Search lists using filter.

3. What is a Lambda?

A Lambda is simply a block of code enclosed in curly braces { }. You declare parameters on the left side of the arrow ->, and the executable code on the right side.
kotlin
12345678
fun main() {
    // A lambda assigned to a variable!
    // Type is: (Int, Int) -> Int
    val multiply = { a: Int, b: Int -> a * b }
    
    // Executing the lambda
    println(multiply(5, 4)) // Outputs 20
}

*Notice there is no return keyword in a lambda! The result of the LAST line of code inside the lambda is automatically returned.*

4. The Magic it Keyword

If a Lambda only takes exactly ONE parameter, Kotlin provides a wonderful shortcut. You don't have to name the parameter or write the ->. Kotlin implicitly names that single parameter it.
kotlin
123456789
fun main() {
    // Explicit way
    val square: (Int) -> Int = { num -> num * num }
    
    // Idiomatic Kotlin way using 'it'
    val fastSquare: (Int) -> Int = { it * it }
    
    println(fastSquare(5)) // Outputs 25
}

5. Trailing Lambda Syntax

This is Kotlin's most famous syntax rule. If a Higher-Order function takes a Lambda as its very last parameter, you can close the parentheses () early and write the Lambda {} *outside*!
kotlin
1234567891011121314
// A function taking a String and a Lambda
fun processData(data: String, action: (String) -> Unit) {
    action(data)
}

fun main() {
    // Without trailing lambda
    processData("Hello", { println(it.uppercase()) })
    
    // WITH Trailing Lambda (Idiomatic Kotlin!)
    processData("Hello") { 
        println(it.uppercase()) 
    }
}

6. Processing Collections (map, filter)

Lambdas make working with Lists incredibly powerful and readable. These operations do not modify the original list; they return a *brand new list*.

#### map (Transforming) map applies the lambda to every item in the list and returns a new list of the results.

kotlin
12345
val numbers = listOf(1, 2, 3, 4)
// Multiplies every number by 10
val doubled = numbers.map { it * 10 } 

println(doubled) // [10, 20, 30, 40]

#### filter (Filtering) filter keeps items where the lambda evaluates to true.

kotlin
12345
val numbers = listOf(1, 2, 3, 4, 5, 6)
// Keeps only even numbers
val evens = numbers.filter { it % 2 == 0 } 

println(evens) // [2, 4, 6]

#### Chaining Operations Because these return new lists, you can chain them together elegantly!

kotlin
1234567
val prices = listOf(5, 12, 8, 20)

val processed = prices
    .filter { it > 10 }   // Keep 12, 20
    .map { it * 2 }       // Double them: 24, 40
    
println(processed) // [24, 40]

7. Common Mistakes

  • Using return inside a lambda: Using the return keyword inside a standard lambda will actually try to return from the *enclosing function* (like main), not just the lambda. Remember: the last line of the lambda is automatically the return value!
  • Overusing it: If a lambda contains complex logic over multiple lines, using it makes the code hard to read. Explicitly name your parameter (e.g., { student -> student.grade > 90 }).

8. Best Practices

  • Embrace Trailing Lambdas: This syntax is used everywhere in Kotlin (especially in Jetpack Compose UI for Android). Always move the lambda outside the parentheses if it is the last argument.

9. Exercises

  1. 1. Create a listOf names: "Alice", "Bob", "Amanda", "Charlie".
  1. 2. Use .filter { ... } to find names that start with "A".
  1. 3. Use .map { ... } to convert those names to uppercase.
  1. 4. Print the final list.

10. MCQs with Answers

Question 1

What is a Lambda expression?

Question 2

What symbol separates the parameters from the body in a Lambda?

Question 3

If a Lambda only takes ONE parameter, what is the implicit name Kotlin assigns to it?

Q4. Does a Lambda use the return keyword to return data? a) Yes b) No, the result of the last line is automatically returned Answer: b) No, the last line is implicitly returned.
Question 5

What is the Trailing Lambda syntax rule?

Question 6

Which collection method evaluates a boolean condition and keeps only the items that return true?

Question 7

Which collection method transforms every item in a list and returns a new list?

Q8. Does .map { } modify the original list? a) Yes b) No, it returns a brand new list Answer: b) No, it returns a new list.

Q9. Is numbers.filter { it > 5 }.map { it * 2 } valid syntax in Kotlin? a) Yes, functional operations can be chained b) No Answer: a) Yes.

Question 10

Why are Lambdas preferred over standard functions for things like .map?

11. Interview Questions

  • Q: Explain what the it keyword represents in Kotlin Lambdas. What is the condition for using it?
  • Q: What is Trailing Lambda syntax? Why do modern Kotlin frameworks (like Jetpack Compose) rely on it so heavily? (Answer: Because it allows function calls to look like native language structures, building clean, readable hierarchical blocks).

12. Summary

Lambdas are the heartbeat of modern Kotlin. By combining the it keyword with Trailing Lambda syntax, Kotlin allows developers to write dense, powerful data transformations in highly readable, almost English-like sentences. Mastering map and filter will change the way you write code forever.

13. Next Chapter Recommendation

While Kotlin protects against NullPointerExceptions, your code can still crash if you try to open a file that doesn't exist or divide by zero. In Chapter 20: Exception Handling, we will learn how to handle unexpected crashes gracefully using try/catch blocks.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·