Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array in Kotlin with values?

Tags:

arrays

kotlin

In Java an array can be initialized such as:

int numbers[] = new int[] {10, 20, 30, 40, 50} 

How does Kotlin's array initialization look like?

like image 535
Lars Blumberg Avatar asked Jul 12 '15 09:07

Lars Blumberg


People also ask

How do I assign a value to an array in Kotlin?

In Kotlin There are Several Ways. Then simply initial value from users or from another collection or wherever you want. var arr = Array(size){0} // it will create an integer array var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.


1 Answers

val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50) 

See Kotlin - Basic Types for details.

You can also provide an initializer function as a second parameter:

val numbers = IntArray(5) { 10 * (it + 1) } // [10, 20, 30, 40, 50] 
like image 145
Maroun Avatar answered Oct 10 '22 17:10

Maroun