Kotlin Array - forEach() Function



The Kotlin array forEach() function is used to perform a given action on each element of an array or collection.

This function (forEach) is one of the loop statements that are more commonly used to execute. Other loops, such as the while loop, are used to retrieve each element of an array or collection.

Syntax

Following is the syntax of Kotlin array forEach() function −

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

Parameters

This function accepts an action as parameter.

Return value

This function returns elements of the given array.

Example 1

Following is the basic example to demonstrate the use of forEach() function −

fun main(args: Array<String>){
   // let's create an array
   var list = arrayOf<String>("tutorialspoint", "Hyderabad", "India")
   //iterate each element using forEach
   list.forEach({
       println(it)
   })
}

Output

On execution of the above code we get the following result −

tutorialspoint
Hyderabad
India

Example 2

Now, let's see another example. Here, we use the forEach() function to iterate over all elements of an array −

fun main(args: Array<String>){
   // let's create an array
   var array = arrayOf<Int>(1, 2, 3, 4, 5, 6, 7)
   // iterate each element using forEach
   print("Element of an array: ")
   array.forEach({
      print("$it ")
   })
}

Output

After execution of the above code we get the following output −

Element of an array: 1 2 3 4 5 6 7 

Example 3

The below example creates custom array of type "Tutorial" and displaying all the details using the forEach() function −

fun main(args: Array<String>) {
   // objects
   val tut1 = Tutorial("Kotlin Tutorial", 50000)
   val tut2 = Tutorial("C Tutorial ", 1000000)
   var array = arrayOf<Tutorial>(tut1, tut2)

   array.forEach {
      println("Price of Tutorial, ${it.name} is ${it.price}")
   }
}
// creating the class Tutorial
data class Tutorial(val name: String = "", val price: Int = 0)

Output

The above code produce following output −

Price of Tutorial, Kotlin Tutorial is 50000
Price of Tutorial, C Tutorial  is 1000000
kotlin_arrays.htm
Advertisements