Table of contents
1.
Introduction
2.
Defining an Array in Kotlin
2.1.
Using arrayOf() function
2.2.
Using array constructor
3.
Methods and Operations on Array
3.1.
Accessing the array elements
3.2.
Changing/Modifying an array element
3.3.
Finding array length/size
3.4.
Using get() and set() methods
3.5.
Traversing an array
3.5.1.
Using loops
3.5.2.
Using Range:
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Arrays in Kotlin

Author Akshit Pant
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Starting with the definition of Array, It is the collection or accumulation of similar kinds of data types. This means that collection of int type data is an example of integer type array, collection of char type data is character type array, collection of string type data is string type array, respectively.

Arrays in Kotlin are mutable in nature(unlike Strings), and that means we can perform basic operations(read and write)on the elements of an array. The concept of an array is not new in Kotlin because it is a fundamental data structure that comes almost in all programming languages.

The idea behind using arrays was to implement something that stores a collection of similar data types so that eventually, data elements can be sorted and searched quickly. So, arrays basically help us to store multiple values in a single variable, rather than to create separate variables for every single value. In this blog, we will be covering everything about the declaration, initialization, implementation, Examples, and operations of Arrays in Kotlin.

Defining an Array in Kotlin

Before looking at the Syntax to define an Array in Kotlin, first, we must know that there are two possible ways to define an Array in Kotlin:

  1. Using arrayOf() function
  2. Using array constructor

Using arrayOf() function

The first way is by using the inbuilt library function arrayOf() for the creation of an array by simply passing the values of the elements/content to the function.

Syntax:

// Use of arrayOf()  implicitly
val num = arrayOf(1, 2, 3, 4)      // implicit type is when compiler decides datatype       
// Use of arrayOf() explicitly 
val num = arrayOf<Int>(1, 2, 3)   //explicit type is when user defines datatype


Example for Implicit type is given below.
Code:

fun main(){ 
val arrayName = arrayOf(10, 20, 30, 40, 50)
    for (i in 0..arrayName.size-1)
    {
        print(" "+arrayName[i])
    }
    println()
}


Output:

10 20 30 40 50


Example for Explicit type is given below. 
Code:

fun main(){ 
val arrayName = arrayOf<Int>(100, 200, 300, 400, 500)
    for (i in 0..arrayName.size-1)
    {
        print(" "+arrayName[i])
    }
}


Output:

100 200 300 400 500

Using array constructor

As we all know that Array is a class in Kotlin, So we can utilize the Array constructor to create an array.
Wonders how?
Well, it's simple; keep in mind that the constructor takes two parameters-
 a. Size/maximum capacity of the Array
 b. A function that takes the index of a specified element and returns the element's initial value.

Syntax:

val ans= Arr(10, {i-> i*1})

In this example of Syntax, we are passing the size of our Array (Arr in this case) as ten and a lambda expression which initializes the element values from 0 to 9.

For better understanding, See this example given below.

Code:

fun main() {
    
  val arrName = Array(10, { i -> i * 1 })
    for (i in 0..arrName.size-1)
    {
        println(arrName[i])
    }    
           }


Output:

0
1
2
3
4
5
6
7
8
9

Also, note down the point that, Kotlin also has some built-in factory methods for the creation of arrays of primitive data types, such as byteArray, intArray, etc. Although these classes do not extend the Array class, they have the same methods and features.

Aside from these, Kotlin includes factory methods for creating arrays of primitive data types like byteArray, intArray, short Array, and so on. Although these classes do not extend the Array class, they have the same methods and features.

The factory method for creating an integer array, for example, is:

val ans = intArrayOf(1, 2, 3, 4, 5, 6, 7,8)


Similarly, Other factory methods for creating arrays in Kotlin are-

charArrayOf()                       // for storing array of characters(like a,b,c,d,...)
byteArrayOf()                       // for storing byte data
longArrayOf()                       // for storing large long type values (32-bit number)

Methods and Operations on Array

Some of the important operations on an array like accessing array elements, modifying elements, get() and set(), traversing are shown below:

Accessing the array elements

We can access the element of our Array with the help of the element's index number and then write it inside our square brackets( [....index.....] ).

In this shown example, we can easily access the value of the first element in myDetail by.

Input:

fun main(){ 
val myDetail= arrayOf("Coding", "Ninja", "Blog", "by_Akshit")
println(myDetail[0])
}


Output:

Coding

Changing/Modifying an array element

For changing the value of a specific element in an array, we can use the index number of that element.

Let us understand it with the same example of myDetail in accessing the array element.

So, For changing, say the first element of myDetail Array with "Second"-

val myDetail= arrayOf("Coding", "Ninja", "Blog", "byAkshit")

which is "Coding" here.

add a line of:

myDetail[0] = "Second"

 

Code:

fun main(){ 
val myDetail= arrayOf("Coding", "Ninja", "Blog", "byAkshit")
myDetail[0] = "Second"
println(myDetail[0])
}


Output:

Second

Finding array length/size

In order to find out the number of elements an array has, we can use the variable_name.size function.

Input:

fun main(){ 
val myDetail= arrayOf("Coding", "Ninja", "Blog", "by_Akshit")
println(myDetail.size)
}


Output:

4

Using get() and set() methods

As you know, an array in Kotlin is basically a class. Therefore, we can access the data of a class object via its member functions. The get() and set() functions are said to be member functions.

An array in Kotlin is essentially a class, as we all know. As a result, we can use a class object's member functions to access its data.

Note: The get() and set() are member functions.

The get() method takes only one parameter, which is "the element's index," and returns the item's value at that specific index.

Syntax:

val ans = myDetail.get(0)

On the other hand, the set() method takes two parameters- "the index of the element and value to be inserted."

Syntax:

myDetail.set(1, 3)

Here, Since the index of the element is one and the value to be inserted is 3, it will set the value of the second element(since indexing starts from 0) in the Array to 3.

Let's see this with an example showing the use of the set method.

Code:

fun main(){ 
val myDetail = arrayOf<Int>(10, 20, 30, 40, 50)
    myDetail.set(0, 11)
    myDetail.set(1, 6)
    for (i in myDetail.indices)
    {
        println(myDetail[i])
    }
}


Output:

11
6
30
40
50

Traversing an array

Before learning how to traverse, first, we must know what traversing is.

So traversing is moving across; for example, if you are traveling through a street, you will be passing through all the street lights and people in the way. So traversing in an array is passing through all the elements in that Array.

So, It becomes an important property that they can easily be traversed, and each element of that traversed Array can be accessed, modified, and manipulated easily.

Kotlin supports different possible ways to traverse in an array.

a. Using loops

b. Using Range

Using loops

The easiest, simplest, and most widely used method for traversing an array is using for loop.

Syntax:

 for(i in myDetail.indices)   // i in myDetail.indices is traversing through all indices
 {   println(myDetail[i])     // here myDetail is our array
 }


 Here is an example of traversing using for loop.
Code:

fun main(){ 
val myDetail = arrayOf<Int>(10, 20, 30, 40, 50)
    
    for (i in myDetail.indices)
    {
        println(myDetail[i])
    }
}

 
Output:

10
20
30
40
50


Using Range:

We can get the same result by using the Range. The (..) operator in Kotlin can be used to generate a range, which is an interval between two values (start and end). The in keyword can then be used to traverse through the Range.

Syntax:

for (j in 0..10){
    println(j)    
}

Note that Range also goes like index from 0 to size -1. So, for traversing an array using the Range, we need to implement the loop from 0 to size-1 in the array name.

Let's see this with an example.

Input:

fun main(){  
val myDetail = arrayOf<Int>(10, 20, 30, 40, 50)
    for (i in 0..myDetail.size-1)
    {
        println(myDetail[i])
    }
}

Here note that myDetail is our array name; you can choose your desired name.

Output:

10
20
30
40
50

Check out this problem - Find Duplicate In Array

Must Read Elvis Operator Kotlin

FAQs

1. Is Kotlin Array mutable?
Arrays in Kotlin are mutable in nature(unlike Strings), and that means we can perform basic operations(read and write)on the elements of an array.
 

2. How can we create an empty string in Kotlin?
For creating an empty array in Kotlin, we can use:

val myEmptyArray : Array<Int> = arrayOf()

To verify whether this creates an empty array or not, run this command-

println(myEmptyArray.size)

 

3. Array indexing starts from 0 or 1 if I want to access the first element of an array?
Generally, indexing in an array starts from 0 to ArraySize-1, so if you want to access the first element of your Array, use:

println(arrayName[0])

 

4. Is there any built-in method for getting the max, min of an array without using for loop?
There are a lot of ways for doing so. A straightforward method is sorting the Array using the "array.sort" method, and then the first element will be the min of the Array, and the last element will be the max.

fun main(){  
 val myArray: Array<Int> = arrayOf(60, 30, 20, 50, 100)
    myArray.sort();
    println("Min/FirstElement: ${myArray.first()}")        
    println("Max/LastElement: ${myArray.last()}") 
}

The output will be: 

Min/FirstElement: 20
Max/LastElement: 100

Key Takeaways

Cheers if you reached here!! 

The purpose of this article was to introduce you to the Kotlin Arrays and give some basic idea about how to initialize and use them with their properties and functionalities.

If anyone wants to set up their Kotlin environment for programming, then here is the help.
If you want to learn more about the difference between Java and Kotlin, you can jump to this article which covers them in great detail.

However, learning never stops, and there is more to learn. So head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications. 
Till then, Happy Learning!

Live masterclass