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<String>) { 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
No comments:
Post a Comment