DEV Community

Sanjay Prajapat
Sanjay Prajapat

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

1 2

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay