Bird
0
0

Given the function below, how can you call it by passing an existing IntArray named numbers?

hard📝 Application Q8 of 15
Kotlin - Functions

Given the function below, how can you call it by passing an existing IntArray named numbers?

fun printNumbers(vararg nums: Int) {
    for (num in nums) print("$num ")
}
AprintNumbers(numbers)
BprintNumbers(*numbers)
CprintNumbers(&numbers)
DprintNumbers(numbers.toList())
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to pass arrays to vararg

    To pass an existing array to a vararg parameter, use the spread operator * before the array.
  2. Step 2: Check each option

    printNumbers(*numbers) uses the spread operator correctly. printNumbers(numbers) passes the array as a single argument. printNumbers(&numbers) uses invalid syntax. printNumbers(numbers.toList()) converts to list, which is not accepted by vararg of Int.
  3. Final Answer:

    printNumbers(*numbers) -> Option B
  4. Quick Check:

    Use * to spread array into vararg [OK]
Quick Trick: Use * to spread array when passing to vararg [OK]
Common Mistakes:
MISTAKES
  • Passing array without *
  • Using invalid operators like &
  • Converting array to list incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes