Bird
0
0

Identify the error in this Kotlin code snippet:

medium📝 Debug Q14 of 15
Kotlin - Collections Fundamentals
Identify the error in this Kotlin code snippet:
val nums = listOf(1, 2, 3)
nums.forEach(i -> println(i))
ACalling println inside forEach is not allowed
BMissing parentheses after forEach
CUsing val instead of var for list
DUsing arrow (->) instead of curly braces for lambda
Step-by-Step Solution
Solution:
  1. Step 1: Check lambda syntax in Kotlin

    Kotlin uses curly braces {} for lambdas, not arrow notation like -> outside braces. The arrow is used inside the lambda to separate parameters from body.
  2. Step 2: Identify the incorrect usage

    The code uses i -> println(i) directly after forEach without braces, which is invalid syntax. Correct form is nums.forEach { i -> println(i) }.
  3. Final Answer:

    Using arrow (->) instead of curly braces for lambda -> Option D
  4. Quick Check:

    Lambda needs braces {} around arrow -> [OK]
Quick Trick: Use { param -> code } for lambdas, not (param -> code) [OK]
Common Mistakes:
MISTAKES
  • Using arrow notation without braces
  • Confusing Kotlin lambda syntax with other languages
  • Thinking val vs var affects forEach usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes