- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Explain about Varargs in java?
- Overloading Varargs Methods in Java
- Using Varargs with standard arguments in Java
- How to convert Java Array/Collection to JSON array?
- How to convert JSON Array to normal Java Array?
- convert list to array in java
- Convert array to HashSet in Java
- Method Overloading and Ambiguity in Varargs in Java
- How to convert a Kotlin source file to a Java source file?
- How to convert Java Array to Iterable?
- how to convert Object array to String array in java
- Convert Character Array to IntStream in Java
- Convert LinkedList to an array in Java
- Convert string to char array in Java
- Convert Char array to String in Java

Advertisements