Variable Arguments to a function in Kotlin

Tarun Chawla
2 min readJun 10, 2019

--

Just like any modern programming language, Kotlin allows a variable number of arguments to be passed to a function.

A parameter may be marked with vararg modifier which allows multiple arguments.

Example

fun<T> varArgFunctionType1(vararg params : T){
for(i in params){
when(i){
is Char -> print("It's a character --> ")
is Int -> print("It's a integer --> ")
is String -> print("It's a string --> ")
}
println(i)
}
}
varArgFunctionType1(1,2,4,'a', "Hello world", 45)

Output:

It's a integer --> 1
It's a integer --> 2
It's a integer --> 4
It's a character --> a
It's a string --> Hello world
It's a integer --> 45

Inside the function vararg parameter is seen as Array<T>, means arguments can be accessed as array parameter.

Passing non vararg parameters

Only one parameter may be marked as vararg. If the vararg parameter is not the last one in the list then parameters following the vararg parameter can be passed using named argument syntax.

fun<T> varArgFunctionType2(id : Int, vararg params : T, id2 : Int){
println(id)
println(id2)
for(i in params){
when(i){
is Char -> print("It's a character --> ")
is Int -> print("It's a integer --> ")
is String -> print("It's a string --> ")
}
println(i)
}
}
varArgFunctionType2(1,2,4,'a', "Hello world", id2 = 45)

Spread operator(*)

If we want to pass an array to vararg parameter then we need to unpack/spread the contents of an array using *.

var arrayList = arrayListOf<Char>('d','e')
varArgFunctionType2(1,*arrayList.toArray(), id2 = 45)

Combining spread values

We can pass additional values to vararg parameter along with spread array or combine multiple spread arrays in the same parameter.

varArgFunctionType2(1,*arrayList.toArray(), "hello",*arrayList.toArray(), id2 = 45)

References

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response