.forEach()

Anonymous contributor's avatar
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 type T and performs an action on it.

Example

The following example demonstrates the usage of the .forEach() method:

fun main() {
// Initialize an array of numbers
val numbers = arrayOf(4, 12, 14, 17, 8)
// Use .forEach() to print each element multiplied by 2
numbers.forEach { println(it * 2) }
}

The above code generates the following output:

8
24
28
34
16

All contributors

Contribute to Docs

Learn Kotlin on Codecademy