63

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

2 Answers 2

140

You can use arrayOf(), as in

val literals = arrayOf("January", "February", "March")
Sign up to request clarification or add additional context in comments.

3 Comments

Just a note, really you could do this: 'val literals = arrayOf<String>("January", "February", "March")' but the argument type <String> is already explicit by the content of the array, so it's OK that way and can be omitted.
Or use ["January", "February", "March"]
@yooouuri that is only allowed on annotations and was only just introduced in Kotlin 1.2: kotlinlang.org/docs/reference/…
7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.