Reputation: 5392
Though that may be a silly question, I can't figure out how to declare an array literal grouping some string literals.
For example, let's assume I want the java array ["January", "February", "March"]
.
How can I translate this into the latest kotlin version (today, 12.0.0)
?
What have I tried?
stringArray("January", "February", "March")
Upvotes: 62
Views: 37186
Reputation: 160357
arrayOf
(which translates to a Java Array
) is one option. This gives you a mutable, fixed-sized container of the elements supplied:
val arr = arrayOf("January", "February", "March")
that is, there's no way to extend this collection to include more elements but you can mutate its contents.
If, instead of fixed-size, you desire a variable sized collection you can go with arrayListOf
or mutableListOf
(mutableListOf
currently returns an ArrayList
but this might at some point change):
val arr = arrayListOf("January", "February", "March")
arr.add("April")
Of course, there's also a third option, an immutable fixed-sized collection, List
. This doesn't support mutation of its contents and can't be extended. To create one, you can use listOf
:
val arr = listOf("January", "February", "March")
Upvotes: 7
Reputation: 5016
You can use arrayOf(), as in
val literals = arrayOf("January", "February", "March")
Upvotes: 140