Bird
0
0

Which of the following Kotlin code snippets correctly uses forEach to print each element of the list items?

easy📝 Conceptual Q2 of 15
Kotlin - Collections Fundamentals
Which of the following Kotlin code snippets correctly uses forEach to print each element of the list items?
Aitems.forEach { println(it) }
Bitems.forEach(println(it))
Citems.forEach -> println(it)
Ditems.forEach { print(it.length) }
Step-by-Step Solution
Solution:
  1. Step 1: Syntax of forEach

    The correct syntax uses a lambda expression: forEach { element -> action } or forEach { action(it) }.
  2. Step 2: Analyze options

    items.forEach { println(it) } correctly prints each element. items.forEach(println(it)) is invalid syntax. items.forEach -> println(it) uses incorrect arrow syntax. items.forEach { print(it.length) } prints length, not the element.
  3. Final Answer:

    items.forEach { println(it) } -> Option A
  4. Quick Check:

    Lambda inside forEach must be enclosed in braces [OK]
Quick Trick: Use braces and lambda to print each element [OK]
Common Mistakes:
MISTAKES
  • Using parentheses instead of braces for lambda
  • Trying to pass println(it) directly as argument
  • Confusing arrow syntax in lambdas

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes