Variable Arguments(Varargs in koltin)

Variable Arguments(Varargs in koltin)

In java looks like

public void println(String.. args) { }

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

// 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")
    }
}
fun main(args: Array<String>) {
    printAnimal("Lion", "Cheetah", "Cat", "Hayena")
    print("\n")
    printAnimal2("Elephant","Lion", "Cheetah", "Cat", "Hayena")
}

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 ")
}
fun main(args: Array<String>) {
    // passing reference of function
    passFun(::f1,::f2) //  function 1 , function 2
}

Generic function

fun <T> printAny(vararg varg: T) {
    varg.forEach { println(it) }
}
fun main(args: Array<String>) {
    printAny(34,56,89)
}