What if you could tell your program to do something for every item without writing it over and over?
Why Iterating collections with forEach in Kotlin? - Purpose & Use Cases
Imagine you have a list of your favorite songs and you want to print each song's name one by one. Doing this manually means writing repetitive code for each song, which quickly becomes tiring and messy as your list grows.
Writing separate code lines for each item is slow and boring. It's easy to make mistakes like forgetting a song or mixing up the order. Also, if the list changes, you must rewrite your code every time, which wastes time and causes frustration.
The forEach function lets you tell the program: "For every item in this list, do this action." This means you write the action once, and it automatically applies to all items, no matter how many there are. It keeps your code clean, simple, and easy to update.
println(songs[0]) println(songs[1]) println(songs[2])
songs.forEach { println(it) }With forEach, you can easily perform actions on every item in a collection, making your code shorter, clearer, and adaptable to any list size.
Think about sending a thank-you message to every person who attended your party. Instead of writing a message for each friend, you use forEach to send the same message to everyone automatically.
Manual repetition is slow and error-prone.
forEach automates actions on all items in a collection.
This makes code cleaner, easier to read, and maintain.
Practice
forEach function do when used on a list in Kotlin?Solution
Step 1: Understand the purpose of forEach
TheforEachfunction is designed to execute a given block of code on every element in a collection.Step 2: Compare options with forEach behavior
Only It runs a block of code for each item in the list. correctly describes this behavior. Options B, C, and D describe other functions likemap,remove, andsort.Final Answer:
It runs a block of code for each item in the list. -> Option AQuick Check:
forEach = run code on each item [OK]
- Confusing forEach with map that creates new lists
- Thinking forEach modifies the list itself
- Assuming forEach sorts or filters the list
numbers using forEach in Kotlin?Solution
Step 1: Recall the correct forEach syntax
In Kotlin,forEachis called on the collection with a lambda block:collection.forEach { item -> ... }. The shorthand usesitfor the current item.Step 2: Check each option's syntax
numbers.forEach { println(it) } matches the correct syntax. forEach(numbers) { println(it) } wrongly uses forEach as a function with the list as argument. numbers.forEach(println(it)) incorrectly calls println inside forEach parentheses. numbers.forEach -> println(it) uses an invalid arrow syntax.Final Answer:
numbers.forEach { println(it) } -> Option CQuick Check:
Correct forEach syntax = numbers.forEach { println(it) } [OK]
- Calling forEach as a standalone function
- Passing println(it) directly inside forEach parentheses
- Using arrow (->) outside lambda block
val fruits = listOf("apple", "banana", "cherry")
fruits.forEach { println(it.length) }Solution
Step 1: Understand the code behavior
The listfruitscontains three strings: "apple", "banana", and "cherry". TheforEachprints the length of each string.Step 2: Calculate lengths and output format
"apple" has length 5, "banana" has length 6, "cherry" has length 6. Eachprintlnprints on a new line, so output is: 5 6 6Final Answer:
5 6 6 -> Option BQuick Check:
Print lengths with println = lines of 5,6,6 [OK]
- Assuming output is on one line separated by spaces
- Confusing string length with number of vowels
- Printing the strings instead of their lengths
val nums = listOf(1, 2, 3) nums.forEach(i -> println(i))
Solution
Step 1: Check lambda syntax in Kotlin
Kotlin uses curly braces{}for lambdas, not arrow notation like->outside braces. The arrow is used inside the lambda to separate parameters from body.Step 2: Identify the incorrect usage
The code usesi -> println(i)directly after forEach without braces, which is invalid syntax. Correct form isnums.forEach { i -> println(i) }.Final Answer:
Using arrow (->) instead of curly braces for lambda -> Option DQuick Check:
Lambda needs braces {} around arrow -> [OK]
- Using arrow notation without braces
- Confusing Kotlin lambda syntax with other languages
- Thinking val vs var affects forEach usage
nums, how can you use forEach to print only the even numbers?Solution
Step 1: Understand the condition for even numbers
An even number has zero remainder when divided by 2, soit % 2 == 0checks if a number is even.Step 2: Use if inside forEach to print only even numbers
nums.forEach { if (it % 2 == 0) println(it) } correctly uses an if statement inside the lambda to print only when the condition is true. Other options either print booleans or have incorrect syntax.Final Answer:
nums.forEach { if (it % 2 == 0) println(it) } -> Option AQuick Check:
Use if inside forEach to filter printing [OK]
- Printing boolean results instead of numbers
- Using division instead of modulo for even check
- Placing if after println causing syntax error
Ready to prove it?
Pass the test and this pattern moves unknown
