In this tutorial, we will learn about Array in Kotlin. The array is also known as a collection of homogeneous data elements. In arrays, we store multiple values in contiguous memory locations. Furthermore, we store and fetch data with the help of index numbers.

It is important to note, In kotlin array is not a data type. It is just treated as a collection of the same kind of data elements and There is a dedicated Array class in kotlin which is used to represent these data collections.

Creating an Array in Kotlin:

There are two ways to create array in Kotlin which are:

  • using arrayOf function
  • using Array() constructor

Example Program(Using arrayOf() function):

fun main(args: Array<String>) {  
     // creating array 
    val students = arrayOf("ABC","XYZ","MNO","JKL") 
    for (name in students) {
        println(name)
    }
 }

Output:

ABC
XYZ
MNO
JKL

Example Program(Using Array() Constructor):

The Array constructor takes two parameters which we have to pass while creating an array with the help of Array Constructor which are the size of the array and a function that can return the initial value of each array element given its index.

fun main(args: Array<String>) {  
     // creating array using Array Constructor
    val asc = Array(5) { i -> (i + 1)}
     asc.forEach { 
       println(it)
     }
 }

Output:

1
2
3
4
5

Modifying and Accessing Array Elements:

In Kotlin we have two functions get() and set() which helps us to modify or to access elements of an array.

The set() function:

The set function is used to set a particular element in the array. Inset function we pass two parameters first one it’s index number which we want to change and the second one is a value which we want to set at that particular index. Check out the following example program.

Example Program:

fun main(args: Array<String>) {  
     // creating array 
    val students = arrayOf("ABC","XYZ","MNO","JKL") 
    students.set(1,"JJJ")  //setting element value at particular indexusing set function
    students[3]="KKK" //another way to setting element value at particulat index
    for (name in students) {
        println(name)
    }
 }

Output:

ABC
JJJ
MNO
KKK

The get() function:

The get function is used to get value from particular index from array. The get function only takes a single parameter which is index number from which you want to fetch value.

Example Program:

fun main(args: Array<String>) {  
     // creating array 
    val students = arrayOf("ABC","XYZ","MNO","JKL") 
    println(students.get(1)) //getting value using get function
    println(students[3]) //another way to fetch value from array
 }

Output:

XYZ
JKL