WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Intermediate · question 39 of 100

Explain the difference between a vararg parameter and a regular parameter in Kotlin. Provide an example of using a vararg parameter in a function.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, a regular parameter is a parameter that you specify with a specific data type and it receives a single value passed to it. While a vararg parameter allows a function to accept an arbitrary number of arguments (of the same data type) that can be passed to it as a comma-separated list.

A vararg parameter is defined using the ‘vararg‘ modifier before the parameter type. For example, consider the following function that takes a vararg parameter of type ‘Int‘:

fun sum(vararg nums: Int): Int {
   var result = 0
   for (num in nums) {
      result += num
   }
   return result
}

The ‘sum‘ function can accept zero or more integers as its arguments, which will be stored as an array named ‘nums‘. The ‘result‘ variable is initialized to 0 and then each value passed as the argument to the ‘sum‘ function is added to ‘result‘, resulting in the sum of all the integers passed as parameters.

Here’s an example of how to call the ‘sum‘ function using a vararg parameter:

val result = sum(1, 2, 3, 4, 5)
print(result) // Output: 15

The above call to ‘sum‘ function returns the sum of all the integers passed as arguments, which is 15. Note that you can also pass zero arguments to the ‘sum‘ function and it will still work.

In summary, a vararg parameter allows a function to accept zero or more arguments of the same data type, which are treated as an array within the function body, while a regular parameter receives a single value as its argument.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics