Junior — Senior
Refactoring Kotlin code: fixing errors and improving style
livecode
Task condition
It is necessary to revise the Kotlin fragment below, eliminating compilation issues and making the logic clearer. You need to replace the immutable list with a mutable one, correctly add a new element, implement iteration over the elements in reverse order without unnecessary synchronization, and ensure correct output.
val numbers = mutableListOf(1, 3, 5)
fun main() {
numbers.add(7)
numbers.forEachReversed { value ->
if (value == 3) return@forEachReversed
println(value)
}
println("Done!")
}
fun <T> List<T>.forEachReversed(action: (T) -> Unit) {
this.asReversed().forEach { action(it) }
}