Home » Blog » Functions with vararg Parameters

Functions with vararg Parameters

Varargs allow you to pass any number of arguments by separating them with commas.

  • The vararg modifier turns a parameter into a vararg.
  • This allows calling printAll with any number of string arguments.
  • Thanks to named parameters, you can even add another parameter of the same type after the vararg. This wouldn’t be allowed in Java because there’s no way to pass a value.
  • Using named parameters, you can set a value to prefix separately from the vararg.
  • At runtime, a vararg is just an array. To pass it along into a vararg parameter, use the special spread operator * that lets you pass in *entries (a vararg of String) instead of entries (an Array<String>).
fun printAll(vararg messages: String) 
{                            
    for (m in messages) println(m)
}
printAll("Hello", "Hallo", "Salut", "Hola", "你好")                 

fun printAllWithPrefix(vararg messages: String, prefix: String) 
{  
    for (m in messages) println(prefix + m)
}
printAllWithPrefix(
    "Hello", "Hallo", "Salut", "Hola", "你好",
    prefix = "Greeting: "                                          
)

fun log(vararg entries: String) 
{
    printAll(*entries)                                             
}

 

Leave a Reply

Your email address will not be published.