Convert Kotlin Array to Java varargs


Varargs, also known as "variable arguments" is a new mechanism in Java by which methods in Java can accept zero or multiple number of arguments. Before this mechanism, the only option available to achieve this type of functionality was "method overloading", but that also required multiple lines of boilerplate code.

In this article, we will see how we can use Varags in Kotlin to call a function multiple times based on different types of arguments. The following example demonstrates how we can use this Varags keyword.

Example

fun main() {
   // calling the function with 4 arguments and
   // passing 3 arguments as recurring call to the function
   val sumOf4Numbers = sum(12, sum(2, 4, 6))
   println("Sum of 4 numbers: " +sumOf4Numbers)
   // calling the same function with 3 arguments and
   // passing 2 arguments as recurring call to the function
   val sumOf3Numbers = sum(12, sum(2, 6))
   println("Sum of 3 numbers: " +sumOf3Numbers)
   // calling the same function with 2 arguments
   val sumOf2Numbers = sum(12, 2)
   println("Sum of 2 numbers: " +sumOf2Numbers)
   // calling the same function without any argument
   val sumOf0Numbers = sum()
   println("Sum of 0 numbers: " +sumOf0Numbers)
}

fun sum(vararg xs: Int): Int = xs.sum()

Output

Once the above piece of code is executed, it will generate the following output

Sum of 4 numbers: 24
Sum of 3 numbers: 20
Sum of 2 numbers: 14
Sum of 0 numbers: 0

Updated on: 23-Nov-2021

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements