Bird
0
0

You want to create an array of size 4 where each element is its index squared (0, 1, 4, 9). Which Kotlin code correctly does this?

hard📝 Application Q15 of 15
Kotlin - Collections Fundamentals
You want to create an array of size 4 where each element is its index squared (0, 1, 4, 9). Which Kotlin code correctly does this?
A<code>val arr = Array(4) { index -> index * index }</code>
B<code>val arr = arrayOf(4) { index -> index * index }</code>
C<code>val arr = intArrayOf(4) { index -> index * index }</code>
D<code>val arr = Array(4) { -> it * it }</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand array initialization with lambda

    Kotlin's Array(size) { index -> value } creates an array where each element is initialized by the lambda using the index.
  2. Step 2: Check each option

    val arr = Array(4) { index -> index * index } uses explicit lambda parameter index and correctly computes index squared. val arr = arrayOf(4) { index -> index * index } is invalid because arrayOf does not take a size and lambda. val arr = intArrayOf(4) { index -> index * index } is invalid syntax for the intArrayOf factory function. val arr = Array(4) { -> it * it } has invalid lambda syntax where it is undefined.
  3. Final Answer:

    val arr = Array(4) { index -> index * index } -> Option A
  4. Quick Check:

    Use Array(size) with index lambda for computed values [OK]
Quick Trick: Use Array(size) with index lambda for computed elements [OK]
Common Mistakes:
MISTAKES
  • Confusing it with index in lambda
  • Using arrayOf() for dynamic initialization
  • Not using lambda for element computation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes