Use forEach in Kotlin

  1. the forEach Loop in Kotlin
  2. Use forEach to Access List Items in Kotlin
  3. Use forEach to Perform Action on a List Item in Kotlin
  4. Use a Nested forEach Loop in Kotlin

This article will introduce the concept and use of the forEach loop in Kotlin.

the forEach Loop in Kotlin

Kotlin forEach is an iteration loop that allows you to access items of a collection or list and perform actions on each item. We can also do the same with the for loop, but using multiple for loops can quickly make your code messy.

On the other hand, forEach makes your code more concise and easy to read. It can be more useful when using it as a functional operator.

We will use forEach to access items on a list in this article.

Syntax:

list_name.forEach {
    //statements
}

Use forEach to Access List Items in Kotlin

We will start with a simple example where we access all the items on a list.

fun main(args: Array<String>) {
    var myList = listOf("Hello", "Welcome", "to", "Kotlin", "Tutorials")
    myList.forEach {
        println(it)
    }
}

Output:

Access a List Item

Use forEach to Perform Action on a List Item in Kotlin

Now, we know how to access the items. Let’s try to perform actions on them.

For this example, we will create an integer list. We will then use forEach to iterate through each item and multiply it by 3.

fun main(args: Array<String>) {
    var myList = listOf<Int>(3, 7, 11, 42, 50)

    myList.forEach {
        println(it*3)
    }
}

Output:

Access and Perform Action on a List Item

Use a Nested forEach Loop in Kotlin

We can also nest forEach under one another. The example below demonstrates the use of nested forEach in Kotlin.

fun main(args: Array<String>) {
    var myList = listOf<Int>(1, 2)

    myList.forEach {
        println(it)
        println()
        myList.forEach {
            println(it*3)
        }
        println()
    }
}

Output:

Nested foreach Example

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.