
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
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