Twitter LogoFacebook Logo
Arrays
Array in Kotlin
By: King

An Array is a group of similar items put together in one object.

Syntax

arrayOf(a, b, c, ...n)

arrayOf<Type>(a, b, c, ...n)

In the first syntax, it is creating an array without specifying a type. This is called implicit type declaration.


In the second syntax, we are specifying the type of elements that the array will hold. This is called explicit type declaration.

val fruits= arrayOf("Apple", "Banana", "Oranges")

In the above example, we used the implicit type declaration to create an array call fruits with 3 strings elements.

val fruits = arrayOf<String>("Apple", "Banana", "Oranges")

Primitive type arrays

Kotlin also have other built-in factory functions to create arrays for primitive types - Integers, Floats, Double, etc.

intArrayOf(1, 2, 3)

In the example, intArrayOf() will create an array with 3 elements - 1, 2, and 3.

Other primitive TypeOf functions

doubleArrayOf()

floatArrayOf()

byteArrayOf()

shortArrayOf()

longArrayOf()

charArrayOf()

booleanArrayOf()

ubyteArrayOf()

uintArrayOf()

ulongArrayOf()

ushortArrayOf()

Accessing and Modifying Values of the Array

An array stores a collection of items call elements. Each element is labeled by an index starting from 0.

val fruits = arrayOf("Cherry", "Watermelon", "Grape")

In the code snippet, the array - fruits - have 3 elements.


"Cherry" is the first element, "Watermelon" is the second element, and "Grape" is the third element.

The index for "Cherry" will be 0 since it is the first element in the array. The index for "Watermelon" will be 1 and the index for "Grape" will be 2.

There are 2 methods we can use to get the values from an array. 


The first method is to use the square brackets [ ]  and indicate which element you want to get.

The second method is to use the get() function.  

val fruit = fruits[1]


println(fruit)

In the example, it will print out "Watermelon" because [1] is asking to get the element with the index 1.

val fruit = fruits.get(2)

In the example, it will print out "Grape." Using the get() function is the same as using the square brackets - [ ]. It accepts an index for the element you want to retrieve.

How to set or change the value of the elements

To set the values is similar to getting the values. There are 2 methods of doing it.


The first method is to use the square brackets - [ ] - to reference the element slot you want to modify.

The second method is to use the set() function.

fruits[1] = "Durian"

val fruit = fruits[1]

println(fruit)

In the above example, it will print out "Durian" because the value from slot 1 - [1] - is changed from "Watermelon" to "Durian."

fruits.set(1, "Tangerine")

The set() function takes 2 arguments: (1) the index you want to set and (2) the new value for the slot.


Sign In