Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Kotlin: varargs : Variable number of arguments

By using 'vararg' modifier, you can define a function that Takes Variable Number of arguments. If you would like to know, basics of vararg in Java, you can go through my below post.

https://self-learning-java-tutorial.blogspot.com/2014/02/varargs-methods-with-variable-number-of.html

Ex
fun sumOf(vararg numbers: Int): Int {

}

Above function takes variable number of integer arguments and return an integer.

VarargsDemo.kt
fun sumOf(vararg numbers: Int): Int {
var sum: Int = 0;

for (i in numbers) {
sum = sum + i
}

return sum
}

fun main(args: Array) {
println("Sum of (1, 2, 3) : ${sumOf(1, 2, 3)}")
println("Sum of (13, 22, 13, 5, 3) : ${sumOf(13, 22, 13, 5, 3)}")
}


Output
Sum of (1, 2, 3) : 6
Sum of (13, 22, 13, 5, 3) : 56




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Kotlin: varargs : Variable number of arguments

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×