Recall & Review
beginner
What does the
forEach function do in Kotlin collections?It runs a given block of code on each item in the collection, one by one.
Click to reveal answer
beginner
How do you write a
forEach loop to print each element in a list called numbers?numbers.forEach { number -> println(number) }
Click to reveal answer
intermediate
Can you modify elements inside a
forEach loop in Kotlin?No,
forEach is used for actions like printing or logging. To change elements, use map or other transformation functions.Click to reveal answer
intermediate
What is the difference between a
for loop and forEach in Kotlin?for is a language construct that can be used with any iterable, while forEach is a function that takes a lambda and runs it on each element.Click to reveal answer
beginner
Write a
forEach example that prints each string in a list with its length.val words = listOf("apple", "banana", "cherry")
words.forEach { word -> println("$word has ${word.length} letters") }
Click to reveal answer
What type of argument does
forEach take in Kotlin?✗ Incorrect
forEach takes a lambda function that is called for each element in the collection.Which of these is a correct way to use
forEach on a list items?✗ Incorrect
The correct syntax is calling
forEach on the collection with a lambda: items.forEach { println(it) }.Can
forEach be used to change the elements of a mutable list directly?✗ Incorrect
forEach is for running code on each element, not for changing elements. Use map or direct indexing for changes.What will this code print?
listOf(1, 2, 3).forEach { println(it * 2) }✗ Incorrect
Each element is multiplied by 2 and printed: 2, 4, 6.
Which Kotlin collection function is best for transforming elements instead of just iterating?
✗ Incorrect
map creates a new collection by transforming each element.Explain how to use
forEach to print all elements in a Kotlin list.Think about how you tell the list to do something with each item.
You got /3 concepts.
Describe the difference between
forEach and a for loop in Kotlin.Consider how each handles looping and control flow.
You got /4 concepts.