.forEach()
Anonymous contributor
Published Nov 2, 2024
Contribute to Docs
In Kotlin, the .forEach()
method iterates over elements in a collection (array, list, or set) and performs the provided action on each element. It does not modify the original collection or return a new one, making it useful for operations with side effects like printing or logging.
Syntax
fun <T> Iterable<T>.forEach(action: (T) -> Unit)
Or alternatively:
fun <T> Array<T>.forEach(action: (T) -> Unit)
T
: The type of the elements in the collection (or array).action
: A function that takes an element of typeT
and performs an action on it.
Example
The following example demonstrates the usage of the .forEach()
method:
fun main() {// Initialize an array of numbersval numbers = arrayOf(4, 12, 14, 17, 8)// Use .forEach() to print each element multiplied by 2numbers.forEach { println(it * 2) }}
The above code generates the following output:
824283416
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Kotlin
Learn Kotlin, the expressive, open-source programming language developed by JetBrains.Beginner Friendly9 hours