Introduction
You use forEach to go through each item in a list or collection easily, doing something with each item without writing a loop yourself.
collection.forEach { item -> // action with item }
val numbers = listOf(1, 2, 3) numbers.forEach { number -> println(number) }
val fruits = listOf("apple", "banana", "cherry") fruits.forEach { println("I like $it") }
val names = listOf("Anna", "Bob", "Cara") names.forEachIndexed { index, name -> println("Person $index is $name") }
fun main() { val colors = listOf("red", "green", "blue") colors.forEach { color -> println("Color: $color") } }
forEach function do when used on a list in Kotlin?forEach function is designed to execute a given block of code on every element in a collection.map, remove, and sort.numbers using forEach in Kotlin?forEach is called on the collection with a lambda block: collection.forEach { item -> ... }. The shorthand uses it for the current item.val fruits = listOf("apple", "banana", "cherry")
fruits.forEach { println(it.length) }fruits contains three strings: "apple", "banana", and "cherry". The forEach prints the length of each string.println prints on a new line, so output is:
5
6
6val nums = listOf(1, 2, 3) nums.forEach(i -> println(i))
{} for lambdas, not arrow notation like -> outside braces. The arrow is used inside the lambda to separate parameters from body.i -> println(i) directly after forEach without braces, which is invalid syntax. Correct form is nums.forEach { i -> println(i) }.nums, how can you use forEach to print only the even numbers?it % 2 == 0 checks if a number is even.Pass the test and this pattern moves unknown