Bird
0
0

Identify the error in this Kotlin code snippet:

medium📝 Debug Q6 of 15
Kotlin - Collections Fundamentals
Identify the error in this Kotlin code snippet:
val numbers = listOf(4, 5, 6)
numbers.forEach(println(it))
Aprintln cannot be used inside forEach
BThe list cannot be iterated with forEach
CIncorrect syntax: lambda must be inside braces, not as a function call
DMissing semicolon after forEach
Step-by-Step Solution
Solution:
  1. Step 1: Analyze syntax

    The code uses forEach(println(it)), which is invalid because println(it) is a function call, not a lambda.
  2. Step 2: Correct usage

    It should be forEach { println(it) } with braces enclosing the lambda.
  3. Final Answer:

    Incorrect syntax: lambda must be inside braces, not as a function call -> Option C
  4. Quick Check:

    Lambda expressions require braces in forEach [OK]
Quick Trick: Use braces for lambda, not parentheses [OK]
Common Mistakes:
MISTAKES
  • Passing function call instead of lambda
  • Using parentheses instead of braces for lambda
  • Assuming forEach accepts direct function calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes