Kotlin: string array literal code it simply

Kotlin Programming

Question or issue of Kotlin Programming:

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

How to solve this issue?

Solution no. 1:

You can use arrayOf(), as in

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

Solution no. 2:

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

Hope this helps!