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.