Kotlin Array forEach()

Kotlin Array forEach()

In Kotlin, the Array forEach() function is used to iterate over each element of an array and perform a specified action for each element. It is a concise way to iterate over the elements without the need for explicit loops like For loop, or While loop.

This function is helpful when you want to apply a specific operation to each element of an array.

In this tutorial, we’ll explore the syntax of the forEach() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the forEach() function is as follows:

fun <T> Array<out T>.forEach(action: (T) -> Unit)

where

ParameterDescription
actionA lambda function that takes the element of array as argument.
Parameters of Array first() function

The forEach() function takes a lambda function as an argument, which specifies the action to be performed on each element of the array. It does not return any value.

Examples

1. Using forEach() to Print Elements of an Array

In this example, we’ll use forEach() to iterate over an array of numbers and print each element.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)

    // Using forEach() to print each element
    numbersArray.forEach { println("Element: $it") }
}

Output

Element: 10
Element: 20
Element: 30
Element: 40
Element: 50

2. Using forEach() to Calculate the Sum of Array Elements

In this example, we’ll use forEach() to iterate over an array of numbers and calculate the sum of all elements.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(10, 20, 30, 40, 50)
    var sum = 0

    // Using forEach() to calculate the sum of array elements
    numbersArray.forEach { sum += it }

    // Printing the original array and the result
    println("Numbers Array: \n${numbersArray.contentToString()}\n")
    println("Sum of Array Elements: \n$sum")
}

Output

Numbers Array: 
[10, 20, 30, 40, 50]

Sum of Array Elements: 
150

In this example, the forEach() function is used to iterate over an array of numbers and calculate the sum of all elements. The original array and the resulting sum are printed to the console.

Summary

In this tutorial, we’ve covered the forEach() function in Kotlin arrays, its syntax, and how to use it to iterate over each element and perform specific actions.