Array

An array is a data structure consisting of a set of elements or values with each element possessing at least one index or key. Arrays are very useful in storing collections of elements you wish to utilize later on in a program.

In Kotlin, arrays are created using the arrayOf() library method. The values you wish to store in the array are passed in a comma-separated sequence:

val names = arrayOf("Tobi", "Tonia", "Timi")

Each array value has a unique index that both specifies its position in the array and can be used to retrieve the value later on. The set of indices in an array starts with the index, 0, and progresses with an increment of 1.

The value held in any given index position of an array can be retrieved by either calling the Array#get() method or by using the [] operation:

val numbers = arrayOf(1, 2, 3, 4)
println(numbers[0]) // Prints 1
println(numbers.get(1)) // Prints 2

At any point in time, the value at a position of an array can be changed:

val numbers = arrayOf(1, 2, 3, 4)
println(numbers[0]) // Prints 1
numbers[0] = 23
println(numbers[0]) // Prints 23

You can check the size of an array at any time with its length property:

val numbers = arrayOf(1, 2, 3, 4)
println(numbers.length) // Prints 4
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225