user6008330
user6008330

Reputation:

How to initiate String array in Kotlin?

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

Upvotes: 11

Views: 15489

Answers (6)

Jose
Jose

Reputation: 2769

array of strings can be initialized with square brackets too.

values = [ "a", "b" ]

Upvotes: 1

Bharat Vasoya
Bharat Vasoya

Reputation: 361

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

Upvotes: 4

Ankit Kumar
Ankit Kumar

Reputation: 3723

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() })

Upvotes: 2

Sergey Emeliyanov
Sergey Emeliyanov

Reputation: 6991

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

Upvotes: 1

AskNilesh
AskNilesh

Reputation: 69754

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

Upvotes: 1

Denysole
Denysole

Reputation: 4061

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

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

Upvotes: 22

Related Questions