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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more