What is "forEach()" method in Kotlin?
Kotlin is a contemporary programming language noted for its simple syntax and extensive feature set. Developers commonly utilize it for Android app development and Java Virtual Machine (JVM) applications.
The forEach() method
The forEach() function loops across collections, doing the specified action on each element. This method makes it easier to conduct operations on each collection element, whether it's a list, array, or other data structure.
Syntax
The basic syntax of the forEach() method is as follows:
collection.forEach { element -> // Perform operation on 'element'}
collectionrepresents the collection you want to iterate through.elementrepresents the placeholder for the current element being processed.
Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.
Code
Let’s demonstrate the usage of the forEach() method with the code given below.
Suppose we have a list of numbers, and we want to calculate the squares of each number present in the list.
fun main() {val numbers = listOf(1, 2, 3, 4, 5)println("Original Numbers: $numbers")numbers.forEach { number ->println("Square of $number: ${number * number}")}}
Code explanation
Line 1–2: Firstly, we define a list of numbers.
Line 4: Next, we display the original list of numbers.
Line 6–7: Finally, we use the
forEach()method to iterate through thenumberslist, and apply the operation to square each element. We print the resulting squares of numbers on the console.
Output
Upon execution, the code calculates the squares of each number in the list by using the forEach() method.
The output of the code looks like this:
Original Numbers: [1, 2, 3, 4, 5]Square of 1: 1Square of 2: 4Square of 3: 9Square of 4: 16Square of 5: 25
Conclusion
Therefore, the forEach() method in Kotlin is a powerful tool for iterating through collections and performing operations on their elements. It is an important developer asset, given its improved readability and code efficiency. It helps optimize data processing tasks by using this function.
Free Resources