DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Updated on • Originally published at sanjayprajapat.hashnode.dev

Variable Arguments(Varargs in koltin)

To pass variable number of arguments to a function. We can declare function with varargs parameter.

In java looks like

public void println(String.. args) { }

// allow function to accept number of arguments 
fun printAnimal(vararg animals:String):Unit{
    for (animal in animals) {
        print("\n $animal")
    }
}

fun printAnimal2(a1: String, vararg animals:String):Unit{
    print("first -> $a1") // elephant    // first argument goes in starting parameter 
    for (animal in animals) {
        print("\n $animal")
    }
}
Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {
    printAnimal("Lion", "Cheetah", "Cat", "Hayena")
    print("\n")
    printAnimal2("Elephant","Lion", "Cheetah", "Cat", "Hayena")
}
Enter fullscreen mode Exit fullscreen mode

Passing List of Function to function

fun passFun(vararg funs:()->Unit){
   for (f in funs) {
       f() // to call function 
   }
}
fun f1(){
    print("function 1 ,")
}
fun f2(){
    print("function 2 ")
}

Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {
    // passing reference of function
    passFun(::f1,::f2) //  function 1 , function 2
}

Enter fullscreen mode Exit fullscreen mode

Generic function

fun <T> printAny(vararg varg: T) {
    varg.forEach { println(it) }
}

Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {
    printAny(34,56,89)
}

Enter fullscreen mode Exit fullscreen mode

Original post on sanjayprajapat.hashnode.dev

Top comments (0)