DEV Community

Cover image for You can pass variable arguments in a Kotlin function
Ted Hagos
Ted Hagos

Posted on • Originally published at workingdev.net on

5

You can pass variable arguments in a Kotlin function

Functions in Kotlin, like in Java, can also accept an arbitrary number of arguments. The syntax is a bit different from Java, instead of using three dots after the type ... , we use the vararg keyword instead.

fun<T> manyParams(vararg va : T) {  // (1)
  for (i in va) { // (2) 
    println(i)
  }
}

fun main(args: Array<String>) {
  manyParams(1,2,3,4,5)  // (3)
  manyParams("From", "Gallifrey", "to", "Trenzalore")  // (4) 
  manyParams(*args) // (5) 
  manyParams(*"Hello there".split(" ").toTypedArray()) // (6)
}
Enter fullscreen mode Exit fullscreen mode

(1) The vararg keyword lets us accept multiple parameter for
this function. In this example, we declared a function that has a typed
parameter; it’s generic. We didn’t have to declare it as generic in order to
work with variable arguments, we just chose to so that it can work with a
variety of types

(2) This is a simple looping mechanism so that we can print each item in the argument

(3) We can pass Ints, and we can pass as many as we want because manyParams accepts variable number of arguments

(4) It works with Strings as well

(5) Like in Java, we can pass an array to a function that accepts variable arguments. We need to use spread operator * to unpack the array. It’s like passing the individual elements of the array one by one, manually

(6) The split() member function will return an ArrayList, you can convert it to an Array , then use the spread operator so you can pass it to a vararg function

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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