Kotlin Array

Learn via video courses
Topics Covered

Overview

An array in Kotlin is a fundamental data structure that allows you to organize and store collections of elements of the same data type in a sequential manner. They provide a simple yet powerful way to manage data, access individual items, and perform various operations efficiently. An array in Kotlin is used extensively for tasks ranging from storing numeric values to managing complex data sets. To learn more about an array in Kotlin, let's dive in.

Arrays in Kotlin

An array in Kotlin is a systematic arrangement of elements of same data type, each identified by an index. These indices typically start from 0 and increment by one for each subsequent element. An array in Kotlin plays a pivotal role in programming as they provide a structured way to store and manage data, making it easy to perform operations on entire collections of values.

For instance, consider a scenario where there is a requirement to store the names of 1000 students. Rather than creating a distinct string variable for each student, a more efficient approach involves defining a single array of strings with a capacity of 1000.

Some Basic Properties Of Arrays

Here are some basic properties of arrays:

  • Homogeneous Elements:
    An array in Kotlin store elements of the same data type. For example, an array of integers will only contain integers, and an array of strings will only contain strings.
  • Fixed Size:
    An array in Kotlin has a fixed size that is determined when the array is created. This size cannot be changed dynamically.
  • Indexing:
    Elements in an array in Kotlin are accessed using an index, which is an integer value that starts from 0 and goes up to (array size - 1).
  • Contiguous Memory Allocation:
    Array elements are stored in contiguous memory locations. This allows for efficient memory access and iteration.
  • Random Access:
    An array in Kotlin provides constant-time access to individual elements by using their index. This means you can access any element directly without needing to iterate through the entire array.
  • Efficient for Searching:
    If the index of an element is known, retrieving the element is very fast (O(1) time complexity).
  • Insertion and Deletion:
    Inserting or deleting elements in the middle of an array in Kotlin can be inefficient, especially in languages with fixed sizes, as it might require shifting elements to make space or fill gaps.

Creating an Array

An array in Kotlin is represented by the Array class which represents a mutable collection of items of same data type. Unlike native data types, arrays are not built into the language itself. You can define arrays in Kotlin using the following two methods.

Using the arrayOf() Function

To create an array, you can use the arrayOf() function, which involves providing the element values as arguments.

Syntax:

Code:

Output:

Using the Array Constructor

Considering that Array is a class within Kotlin, we have the option of using the Array constructor to establish an array structure. This constructor involves two essential parameters:

  1. The designated size of the array.
  2. A function that takes the index of a specific element and yields the preliminary value of that element.

Syntax:

In the given example, we declare the array size as 3 and integrate a lambda expression. This expression initializes the element values within the array.

Here is a Kotlin program that illustrates the creation of an array using the constructor.

Code:

Output:

Other Factory Methods Available for Creating Arrays

Kotlin also provides predefined factory functions to create arrays of primitive data types, such as byteArray, intArray, shortArray, and more. It is noteworthy that these classes do not extend the Array class but rather implement the same methods and properties.

For instance, to create an integer array, the factory method is as follows.

Code:

These factory methods provide a convenient way to create arrays of primitive data types. Here is a sample usage of each of these methods.

byteArrayOf()

Creates an array of bytes.

Code:

Output:

charArrayOf()

Creates an array of characters.

Code:

Output:

shortArrayOf()

Creates an array of short integers.

Code:

Output:

longArrayOf()

Creates an array of long integers.

Output:

In each example shown above, the respective factory method is used to create an array of the corresponding primitive data type, and then a loop is used to iterate through and print the elements of the created arrays. The output for each example shows the elements of the array being printed one by one.

Accessing and Modifying Arrays

Up to this point, we've learned about the process of creating and initializing arrays in Kotlin. Now, let us learn about the methods of accessing and modifying them. Once again, there exist two approaches for achieving this:

Utilizing the get() and set() Functions

As you're aware, an array in Kotlin essentially functions as a class. Consequently, the data within a class object can be interacted with via its member functions like get() and set().

  • The get() function:
    The get() function takes a single parameter- the index of the desired element. It then returns the value associated with the item present at that particular index.

Syntax:

Explanation:

The provided code snippet returns the first element(i.e. he element with index 0) and stores it in variable num.

  • The set() function:
    The set() function takes two parameters- the index of the targeted element and the intended value for insertion.

Code:

Explanation:

The provided code snippet modifies the second element(i.e. he element with index 1) in the array, setting its value to 3.

Using the Index Operator[ ]

The index operator [ ] proves to be a useful tool for both accessing and altering array contents. For accessing an element within an array in Kotlin, the appropriate syntax is as follows.

Code:

Explanation:

This operation assigns the value of the second element in the array numbers to the variable num.

To modify an array element, we do the following.

Code:

This action effectively modifies the value of the third element (i.e. the element with index 2) within the array numbers to 5.

The index operator, denoted as [ ], is essentially an overloaded operator beneath the surface. In essence, it signifies invocations of the get() and set() member functions.

Below is an example of manipulation of an array in Kotlin, illustrating the creation of an array, alterations to its values, and targeted element access.

Code:

Output:

Traversing Arrays

An inherent characteristic of an array in Kotlin is their programmatic traversal, enabling the manipulation of each individual element. Kotlin allows several techniques for traversing arrays.

Kotlin Program of Array Traversal Using for Loop

The most straightforward and frequently used method for array traversal involves the use of a for-loop.

Syntax:

Code:

Output:

Kotlin Program of Array Traversal Using Range

The same outcome can be achieved by using a range. In Kotlin, a range signifies a span between two values (starting and ending points), which can be established using the (..) operator. Subsequently, traversal through the range becomes feasible by using the in keyword.

Syntax:

The element range within an array in Kotlin spans from 0 to size-1. Consequently, when using a range to traverse an array, we execute a loop that iterates from 0 to size-1 using the array's name as the reference.

Code:

Ouput:

Kotlin Program of Array Traversal Using forEach loop

Another way of achieving the same functionality is forEach loop.

Syntax:

Code:

Output:

Conclusion

  1. An array in Kotlin is used for storing collections of elements of the same data type. They offer constant-time random access to elements through indexing, making them efficient for retrieval.
  2. An array in Kotlin can be created using arrayOf() function and the Array constructor.
  3. The factory methods like byteArrayOf(), charArrayOf(), shortArrayOf(), and longArrayOf(), provide a convenient way to create arrays of primitive data types.
  4. An array in Kotlin can be accessed and modified using the get() and set() functions. The same can also be accomplished using the index operator [].
  5. An array in Kotlin can be traversed using for loop, range and forEach.