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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay