Idea: Passing an array to a `vararg` parameter usi...
# language-proposals
m
Idea: Passing an array to a
vararg
parameter using
vararg
keyword. Reason: Make code easier to read & understand (one keyword in both locations), simplify language (no extra unary
*
operator needed) Esp. helpful for people who are new to Kotlin or have only rarely if ever use spread operators in other languages. Example:
Copy code
ByteString.of(*buffer.toByteArray())
->
Copy code
ByteString.of(vararg buffer.toByteArray())
At the declaration-site
vararg
denotes "variadic number of parameters". At the call-site
vararg
denotes "variadic number of arguments".
3
9
p
As @Dico pointed out you can use spread operator several times and even combine it with other values for the same parameter:
Copy code
ByteString.of(1, *byteArrayOf(2, 3), 4, 5, *byteArrayOf(6, 7))
And
vararg
instead of
*
is less readable in this case.
m
That's an interesting (yet potentially rare) case indeed. Using
vararg
would make it longer and less concise, yes. It could still be more readable and comprehensible esp. in more complex cases where it's not that easy to spot these
*
and immediately see their meaning.
p
I just wish the
*
worked on arrays and Lists. I am always tripped up by it.
m
Yeah arrays are second class citizens in Kotlin (all operators on arrays return lists, which practically forces you to use lists) and yet you have to convert to array to use spread
plus debugging arrays is cumbersome (I always forget to wrap it in
Arrays.toString
and get garbage output)
k