Arrays in Kotlin

By | October 10, 2017

Two main ways to create array in kotlin. Helper function arrayOf() and constructor Array() . 

details of arrayOf() function

to access any element of this array we need to write myArray[index] to get specific value.

It is noted that in array you can assign different data type value . for example

To enforce that all the element of array must be fixed size , we need to use generics . arrayOf<T>

first line of this code example is wrong cause we define it must be integer type array but we assign different data type value inside this array. So If we use generics must follow the data type first.

We also have other utility functions to create arrays of other types such as charArrayOf()booleanArrayOf()longArrayOf()shortArrayOf()byteArrayOf(), and so on. Behind the scenes, using these functions will create an array of their respective Java primitive types. In other words, intArrayOf() will compile to the regular Java primitive type int[]byteArrayOf() will be byte[]longArrayOf() will be long[], and so on.


The Array() Constructor

Now see how to create array With Array(). This constructor requires a size of array and a lamda expression. The lamda expression is to initialize the array with elements

In this code we tell array size is 5 . second part generate value using key or array . so the value of this array 0,2,4,6 and 8


note: we learn lamda expression in another part of this tutorial series


Leave a Reply