Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is vararg in kotlin useless?

Tags:

android

kotlin

I am thinking about vararg (variable arguments) option in kotlin. I know it was here before kotlin in time of java, but I actually never really understand benefit of using it. If i want for example for my function myFun() to take variable number of arguments (let's say Strings), I would create myFun() in a way that it takes List of Strings. I don't see any reason for using vararg.

Is there any benefit of using vararg over List, am I missing something?


2 Answers

vararg gives you freedom to call a function with infinite number of arguments without wrapping them in a collection. Using argument of List type, you are in control of more than just arguments, such as mutability.

This is more opinioned answer.

like image 72
Nikola Despotoski Avatar answered Sep 04 '25 01:09

Nikola Despotoski


You are right, passing a list is one option to avoid vararg.

For you as the implementor of the function there is no real difference, but for the consumer it is. It's a question of function design. How do you want your clients to call your functions.

Passing a list forces the caller to create a list first and populate it with all the items before passing them to the function.

fun foo(list: List<Int>) { ... }
val list: List<Int> = listOf(1,2,3,4,5)
foo(list)

If you offer a function taking a vararg type the way how to call that function changes.

fun bar(vararg items: Int) { ... }
fun bar(1) // just passing one parameter
fun bar(1,2,3) // or maybe three, etc.

Both ways have their usecases.

like image 41
ChristianB Avatar answered Sep 04 '25 02:09

ChristianB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!