11

I would like to know how to start an array similar to this String [] errorSoon = {"Hello", "World"}; in Kotlin. How is done?

1
  • You can use this library function arrayOf("a","b"). Commented Dec 18, 2017 at 12:35

6 Answers 6

22

You can use arrayOf() fuction as it described in Kotlin Basic Type article.
Your code will be the next:

val errorSoon = arrayOf("Hello", "World")
Sign up to request clarification or add additional context in comments.

Comments

4

Declare array at global

names = arrayOf(String())

Now in onCreate method Initialize you array with value

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    //Init array here
    names = arrayOf("Friends List", "Notification")
}

1 Comment

Please add a short description of how your code answers the question. It would help others understand your answer better.
2
val array= arrayOf("Hello", "World")

And there is one more way to create String Array.

// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5, { i -> (i * i).toString() })

Comments

1

Try this arrayOf() to create array in Kotlin

val errorSoon = arrayOf("a", "b", "c")        

to get values from array use below code

for (i in errorSoon.indices) {
    print(errorSoon[i]+" ")
}

You can read more here about it

Comments

1
val errorSoon = arrayOf("Hello", "World")

Comments

1

array of strings can be initialized with square brackets too.

values = [ "a", "b" ]

1 Comment

not supported in Android's Kotlin: "collection literals are outside of annotations"

Your Answer

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