Kotlin Arrays


Kotlin Arrays

Arrays are utilized to store multiple items of the same data type in a single variable, which is an integer or a string with the same variable name.

Arrays are utilized to store multiple items of the same data type in a single variable, which is an integer or a string with the same variable name.

Like any other modern programming language, Kotlin supports arrays and provides a wide range of properties and support functions for managing arrays.

Creating Arrays in Kotlin

To create an array in Kotlin, we use the arrayOf () function and place the values inside the comma-separated list:

Alternatively, the arrayOfNulls () function can create an array of empty elements of a given size.

Primitive type Arrays

Kotlin also has some built-in factory methods for creating arrays of primitive data types.

Other methods are there for creating arrays:

  1. byteArrayOf()
  2. charArrayOf()
  3. shortArrayOf()
  4. longArrayOf()

To Get and Set the Elements of an Array

We can access an array element using the index number inside the square bracket. The Kotlin Array Index starts at zero (0). So if you want to access the fourth element of the Array, you have to enter three as the index.
Kotlin also provides functions such as to get () and sets () for obtaining and setting values in a particular index.

Kotlin Array Length

It provides an array property called size, which gives the size of the Array, i.e., length.

We can also use the count () function to get the size of the Array.

To check if an element exists in an Array.

To check if an element already exists in an array, we can use the in operator with if ... else.

Distinct values from Array

Kotlin allows duplicate values to be stored in an array, but at the same time, you get a set of different values stored in the Array using a separate () member function.

Dropping Elements from Array

To drop elements from the beginning of the last, we can use the drop () or dropLast () function.

Checking an Empty Array

To check if the Array is empty or not, we can use the isEmpty () function. If the Array is empty, the function returns an actual value.