0
0
Kotlinprogramming~20 mins

Iterating collections with forEach in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
forEach Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using forEach?

Consider the following Kotlin code snippet:

val numbers = listOf(1, 2, 3)
numbers.forEach { print(it * 2) }

What will be printed when this code runs?

Kotlin
val numbers = listOf(1, 2, 3)
numbers.forEach { print(it * 2) }
A246
B123
C6
DError: forEach cannot be used on List
Attempts:
2 left
💡 Hint

Remember that forEach applies the given action to each element in the list.

🧠 Conceptual
intermediate
2:00remaining
Which statement about Kotlin's forEach is true?

Choose the correct statement about the forEach function in Kotlin collections.

A<code>forEach</code> can be used to modify the elements of a mutable list directly.
B<code>forEach</code> is a terminal operation that applies a given action to each element.
C<code>forEach</code> returns a new list with transformed elements.
D<code>forEach</code> can only be used with arrays, not lists.
Attempts:
2 left
💡 Hint

Think about what forEach does with the elements and its return type.

🔧 Debug
advanced
2:00remaining
What error does this Kotlin code raise?

Examine the code below:

val items = listOf("a", "b", "c")
items.forEach { it = it.uppercase() }

What error will this code produce?

Kotlin
val items = listOf("a", "b", "c")
items.forEach { it = it.uppercase() }
ATypeError: Cannot assign to 'it' because it is a val
BSyntaxError: Missing lambda arrow
CNullPointerException
DNo error, prints uppercase letters
Attempts:
2 left
💡 Hint

Consider whether the lambda parameter it can be reassigned.

Predict Output
advanced
2:00remaining
What is the output of this Kotlin code using forEachIndexed?

Consider this Kotlin code:

val list = listOf("x", "y", "z")
list.forEachIndexed { index, value -> print("$index$value") }

What will be printed?

Kotlin
val list = listOf("x", "y", "z")
list.forEachIndexed { index, value -> print("$index$value") }
A012
Bxyz
CError: forEachIndexed not found
D0x1y2z
Attempts:
2 left
💡 Hint

Remember forEachIndexed provides both index and element.

📝 Syntax
expert
2:00remaining
Which option causes a compilation error in Kotlin forEach usage?

Which of the following Kotlin code snippets will cause a compilation error?

A
val nums = listOf(1, 2, 3)
nums.forEach { println(it + 1) }
B
val nums = listOf(1, 2, 3)
nums.forEach { val it = it + 1; println(it) }
C
val nums = listOf(1, 2, 3)
nums.forEach(it -&gt; println(it))
D
val nums = listOf(1, 2, 3)
nums.forEach { number -&gt; println(number) }
Attempts:
2 left
💡 Hint

Check the lambda syntax in Kotlin carefully.