Bird
0
0

How can you use forEach to print the index and value of each element in val letters = listOf("x", "y", "z")?

hard📝 Application Q9 of 15
Kotlin - Collections Fundamentals
How can you use forEach to print the index and value of each element in val letters = listOf("x", "y", "z")?
Aletters.forEachIndexed { index, value -> println("$index: $value") }
Bletters.forEach { println(it.index + ": " + it.value) }
Cletters.forEach { index, value -> println("$index: $value") }
Dletters.forEachIndexed { println(it) }
Step-by-Step Solution
Solution:
  1. Step 1: Use forEachIndexed for index and value

    The forEachIndexed function provides both index and element in the lambda parameters.
  2. Step 2: Check correct lambda syntax

    letters.forEachIndexed { index, value -> println("$index: $value") } correctly uses forEachIndexed { index, value -> ... } and prints index and value formatted.
  3. Final Answer:

    letters.forEachIndexed { index, value -> println("$index: $value") } -> Option A
  4. Quick Check:

    Use forEachIndexed for index and element [OK]
Quick Trick: Use forEachIndexed to access index and element [OK]
Common Mistakes:
MISTAKES
  • Using forEach instead of forEachIndexed for index
  • Incorrect lambda parameters
  • Trying to access index and value from 'it'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes