Bird
0
0

Which of the following Kotlin code snippets correctly uses forEach to print all elements of val nums = listOf(1, 2, 3) each on a new line?

easy📝 Syntax Q3 of 15
Kotlin - Collections Fundamentals
Which of the following Kotlin code snippets correctly uses forEach to print all elements of val nums = listOf(1, 2, 3) each on a new line?
Anums.forEach { print(it) }
Bnums.forEach { println(it) }
Cnums.forEach println(it)
Dnums.forEach(println)
Step-by-Step Solution
Solution:
  1. Step 1: Check syntax correctness

    nums.forEach { println(it) } uses the correct lambda syntax with curly braces and println(it) to print each element on a new line.
  2. Step 2: Analyze other options

    nums.forEach println(it) misses braces, causing syntax error. nums.forEach { print(it) } prints without newline. nums.forEach(println) passes a function reference incorrectly.
  3. Final Answer:

    nums.forEach { println(it) } -> Option B
  4. Quick Check:

    Correct forEach print syntax = nums.forEach { println(it) } [OK]
Quick Trick: Use braces and println(it) inside forEach for line-by-line print [OK]
Common Mistakes:
MISTAKES
  • Omitting braces for lambda
  • Using print instead of println for new lines
  • Passing function reference incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes