Junior — Middle
Can you describe the main differences between 'for' and 'forEach' constructs in Kotlin and when to prefer each?
sobes.tech AI
Answer from AI
In Kotlin, the for construct is a classic loop that allows iterating over elements of a collection or range with the possibility to use an index or modify the logic inside the loop. For example:
for (item in list) {
println(item)
}
forEach is an extension function for collections that takes a lambda expression and applies it to each element. It is more declarative and often used for concise code:
list.forEach { item ->
println(item)
}
Main differences:
forallows usingbreakandcontinue,forEachdoes not.- In
forEach, the lambda expression may affect performance in some cases.
Prefer to use for when you need the ability to break the loop or complex logic, and forEach for simple operations on collection elements.