How to initialize an array in Kotlin with values?

In Java, you can initialize an array, for example:

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

What does Kotlin array initialization look like?

+178
arrays kotlin
Jul 12 '15 at 9:20
source share
17 answers
 val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50) 

See Kotlin - Basic Types for Details.

+207
Jul 12 '15 at 9:26
source share

It is worth noting that when using the built-in kotlin tools (for example, intArrayOf() , longArrayOf() , arrayOf() , etc.) you cannot initialize the array with default values ​​(or all values ​​to the desired value) for a given size, instead of this you need to initialize with a call in accordance with the constructor of the class.

 // Array of integers of a size of N val arr = IntArray(N) // Array of integers of a size of N initialized with a default value of 2 val arr = IntArray(N) { i -> 2 } 
+52
Sep 28 '16 at 2:59
source share

Here is an example:

 fun main(args: Array<String>) { val arr = arrayOf(1, 2, 3); for (item in arr) { println(item); } } 

You can also use the playground to check your language capabilities.

+39
Jul 12 '15 at 9:27
source share

There are several ways in Kotlin.

 var arr = IntArray(size) // construct with only size 

Then just the initial value from users or from another collection or anywhere.

 var arr = IntArray(size, { 0 } ) // construct with size and fill array with 0 var arr = IntArray(size, { it * 1 } ) // construct with size and fill with its index 

We can also create an array with a built-in function, for example -

 var arr = intArrayOf(1, 2, 3, 4, 5) // create an array with 5 values 

Another way

 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. 

You can also use doubleArrayOf() or DoubleArray() or any primitive type instead of Int.

+32
Jun 10 '17 at 9:23
source share

In Kotlin, we can create an array using the functions arrayOf() , intArrayOf() , charArrayOf() , booleanArrayOf() , longArrayOf() .

For example:

 var Arr1 = arrayOf(1,10,4,6,15) var Arr2 = arrayOf<Int>(1,10,4,6,15) var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot") var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh") var Arr5: IntArray = intArrayOf(5,10,15,20) 
+19
Jul 09 '18 at 16:38
source share

you can use these methods

 var numbers=Array<Int>(size,init) var numbers=IntArray(size,init) var numbers= intArrayOf(1,2,3) 

Example

 var numbers = Array<Int>(5, { i -> 0 }) 

init represents the default value (initialize)

+5
Jun 01 '17 at 11:02 on
source share

Old question, but if you want to use a range:

 var numbers: IntArray = IntRange(10, 50).step(10).toList().toIntArray() 

Almost the same result as:

 var numbers = Array(5, { i -> i*10 + 10 }) 

result: 10, 20, 30, 40, 50

I think the first option is a little readable. Both work.

+5
Jun 06 '17 at 1:44 on
source share

I think that one thing worth mentioning and not intuitive enough from the documentation is that when you use the factory function to create an array and specify its size, the array is initialized with values ​​equal to their index values. For example, in an array such as: val array = Array(5, { i -> i }) , the initial values ​​are assigned [0,1,2,3,4] and do not say, [0,0,0,0,0] . That's why from the documentation val asc = Array(5, { i -> (i * i).toString() }) gives the answer ["0", "1", "4", "9", "16"]

+3
Jun 23 '17 at 20:58
source share

You can create an Int Array as follows:

 val numbers = IntArray(5, { 10 * (it + 1) }) 

5 - the size of the array Int. The lambda function is the init function of the element. 'it' range at [0.4], plus 1 range at [1.5]

Origin Function:

  /** * An array of ints. When targeting the JVM, instances of this class are * represented as 'int[]'. * @constructor Creates a new array of the specified [size], with all elements * initialized to zero. */ public class IntArray(size: Int) { /** * Creates a new array of the specified [size], where each element is * calculated by calling the specified * [init] function. The [init] function returns an array element given * its index. */ public inline constructor(size: Int, init: (Int) -> Int) ... } 

IntArray class defined in Arrays.kt

+3
Jan 03 '18 at 6:22
source share

You can try the following:

 var a = Array<Int>(5){0} 
+2
Aug 03 '17 at 18:12
source share

You can simply use existing standard library methods , as shown here:

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

It might make sense to use a special constructor:

 val numbers2 = IntArray(5) { (it + 1) * 10 } 

You pass in the size and lambda that describes how to trigger the values. Here is the documentation:

 /** * Creates a new array of the specified [size], where each element is calculated by calling the specified * [init] function. The [init] function returns an array element given its index. */ public inline constructor(size: Int, init: (Int) -> Int) 
+2
Apr 27 '18 at 6:46
source share

In my case, I need to initialize the elements of my box. I fill in the data below the code.

  val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon) val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name) // Use lambda function to add data in my custom model class ie DrawerItem val drawerItems = Array<DrawerItem>(iconsArr.size, init = { index -> DrawerItem(iconsArr[index], names[index])}) Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size) 

Custom Model Class -

 class DrawerItem(var icon: Int, var name: String) { } 
+1
Jul 23 '17 at 8:35
source share

Declare an int array in global

 var numbers= intArrayOf() 

the following onCreate method initializes your array with the value

 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //create your int array here numbers= intArrayOf(10,20,30,40,50) } 
+1
Mar 14 '18 at 5:45
source share

The Kotlin language has specialized classes for representing arrays of primitive types without the overhead of IntArray : for example, IntArray , ShortArray , ByteArray , etc. I must say that these classes have no inheritance relation to the parent Array class, but they have the same set of methods and properties. Each of them also has a corresponding factory function. So, to initialize an array with values ​​in Kotlin, you just need to enter this:

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

... or so:

 val myArr = Array<Int>(5, { i -> ((i+1) * 10) }) myArr.forEach { println(it) } // 10, 20, 30, 40, 50 

Now you can use it:

 myArr[0] = (myArr[1] + myArr[2]) - myArr[3] 

Hope this helps.

+1
Jan 09 '19 at 19:29
source share

I wonder why no one just gave the simplest answers:

 val array: Array<Int> = [1, 2, 3] 

According to one comment on my original answer, I realized that this only works when using annotations in the arguments (which was really unexpected for me).

Kotlin doesn't seem to allow array literals to be created outside of annotations.

For example, look at this code using @Option from the args4j library:

     @Option (
         name = "-h",
         aliases = ["--help", "-?"],
         usage = "Show this help"
     )
     var help: Boolean = false

The option argument "aliases" is of type Array<String>

+1
Apr 26 '19 at 11:49 on
source share

intialize array as follows: val paramValueList : Array<String?> = arrayOfNulls<String>(5)

0
Sep 23 '17 at 6:08
source share
  Arrays Arrays in Kotlin aren't native objects, but instances of the Array class. This is a generic class, see Chapter 8 for a full account of Generics, and you can create arrays of any other type. Creating an array is slightly different in Kotlin in that you have to call a constructor or a factory function that makes the array. Kotlin arrays my be slightly different, but they are JVM Java arrays and work in exactly the same way under the cover. The arrayOf function takes a list of values all of the same type and returns them as an array. For example to create an array of three integers you would use: var a=arrayOf(1,2,3) The array type has get and set functions which accept and index but these are also mapped to the [] operator and so you can write: Int b=a[0] a[0]=5 or Int b=a.get(0) a.set(0,5) You can create an array of any type in the same way. For example: var a=arrayOf(1.2,2.2,3.3) creates an array of floats and var a=arrayOf('a','b','c') 
0
Jan 10 '19 at 7:01
source share



All Articles