string array literal ? How do I code it simply?

ArraysKotlin

Arrays Problem Overview


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")

Arrays Solutions


Solution 1 - Arrays

You can use arrayOf(), as in

val literals = arrayOf("January", "February", "March")

Solution 2 - Arrays

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") 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionloloof64View Question on Stackoverflow
Solution 1 - ArraysHadi HaririView Answer on Stackoverflow
Solution 2 - ArraysDimitris Fasarakis HilliardView Answer on Stackoverflow