Array of Kotlin

An Array is a collection of a values of the same type. When you need to store a list of values, such as numbers, you can store them in an array, insted of declaring separate variables for each number.

Constructor of Array in Kotlin


Syntax of Array in Kotlin

As you can see, constructor of array takes a fix size and an init function to return elements of array. There are multiple ways to create a kotlin array

      • Using Library function
      • Using Array Constructor
      • Using Factory function

Create Array Using Library Function

We can create array in kotlin using library function like arrayOf(), arrayOfNulls().


Library Function Example

Here, we have created an array of size 6 with elements 1, 2, 3, 4, 5 and 6. Note that all the elements are of same data type i.e. Int. Using arrayOfNulls() function, we can create an array as below.


Library Function Example

Here, we have created an array of size 6 and each element in the array is initialized with null value. You must provide data type of element of array while creating array. Here, it is Int.

Create array using Array Constructor


Array Constructor

Parameter of Array constructor takes size of array and an init function that returns elements of array.
Here, we are creating an array of size 6 that has element 0, 1, 4, 9, 16 and 25. Note that all the elements are string not int.

Create array using Factory function

Array of primitives data types have specialised class. Eg, Byte has ByteArray, Int has IntArray, Short has ShortArray and so on. These classes has no inheritance relation with Array class. But each class has same set of methods and properties. Each such class has it’s own factory function. Eg. byteArrayOf() for ByteArray, intArrayOf() for IntArray, floatArrayOf() for FloatArray and so on.


Factory function

Access elements of Array

Let’s say we have an array (named arr) of size n. Each element in array has an index. Indexing in array starts from 0. For example, 1st position element has index 0, 2nd position element has index 1, 3rd position element has index 2 etc.


Output
4

Modify elements of array using indexing property


Output
4
8

Here, we are printing out first the index of the 3rd position, what is 4. After that we modify the element at the same position to 8, so the printed out result will be 8.

Traverse elements of array using loop

Iterate through an array using for loop


Output
1 2 3 4 5 6

Iterate through an array using while loop


Output
1 2 3 4 5 6

Iterate through an array using do while loop


Output
1 2 3 4 5 6

Exercises

What is the output?

What is the output?
Comment the result below 😉

 

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *