Iterating Over Collections
Swipe to show menu
Collections in Kotlin are essential tools that let you group and manage multiple values together. The most commonly used collection is the list, which allows you to store an ordered sequence of items. Collections are important in Kotlin because they help you organize data efficiently and enable you to perform operations, such as searching, sorting, or transforming data, in a clean and readable way. Lists, sets, and maps are the primary collection types in Kotlin, with lists being particularly useful when you need to maintain the order of elements or access them by their position.
Main.kt
In this example, the for loop iterates through each element in the numbers list. On each iteration, the loop variable number takes the value of the current item in the list. The statement sum += number adds the current number to the running total stored in sum. After the loop has visited every element, sum contains the total of all values in the list, which is then printed to the console. This approach makes it easy to process all items in a collection without needing to manage indices or worry about the size of the list.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat