Explain Arrays in Kotlin | Kotlin Tutorial
Explain Arrays in Kotlin | Kotlin Tutorial
In this article, we will cover the following points:
- What is an Array?
- How to create an Array in kotlin?
- How to access the elements of an Array in kotlin?
- How to perform different operations in kotlin, like changing the value of an array and more?
What is an Array?
An array is a collection of elements of similar data types such as integer, char, double, etc., having an index from 0 to n-1. However, it is a good practice to define the length of an array before storing the elements on the particular index. Similar to other programming languages, kotlin extends its support to an Array along with its multiple functionalities.
How to create an array in Kotlin?
There are multiple ways to create an array in the kotlin language:
- arrayOf() function is used to create an array.
Example,
var bikes = arrayOf("Herald", "Honda SB Shine", "Bajaj Pulsar 150", "Royal Enfield")
In this example, var is a keyword used in declaring the array variable, and arrayOf() carries the value by separating it with a comma.
- arrayOf<datatype>() is used to define an array along with the data type of elements.
Example,
var bikes = arrayOf<String>("Herald", "Honda SB Shine", "Bajaj Pulsar 150", "Royal Enfield")
In this example, the var keyword is used to define the array variable that has elements of string data type.
- arrayOfNulls() function is used to define an array of a given size filled with null elements.
There are a few other functions through which you can only create the array of a particular data type, such as byteArrayOf(), intArrayOf(), and more.
How to access the elements of an Array in kotlin?
The element of an array is accessed by using an index number.
Example,
var bikes = arrayOf("Herald", "Honda SB Shine", "Bajaj Pulsar 150", "Royal Enfield")
println(bikes[1])
When we run the above program, the output of the following code is:
Honda SB Shine
It can be accessed by using set and get functions.
get(): It is used to fetch the value from an array.
set(): It is used to set the value in an array at a particular index.
Example,
var bikes = arrayOf("Herald", "Honda SB Shine", "Bajaj Pulsar 150", "Royal Enfield")
println(bikes.get(1))
When we run the above program, it will give the following output:
Honda SB Shine
How to perform different operations in kotlin, like changing the value of an array and more?
- Change the value of an array element
var bikes = arrayOf("Herald", "Honda SB Shine", "Bajaj Pulsar 150", "Royal Enfield")
bikes[0] = Jawa
println(bikes[0])
The output of the following code is:
Jawa
Earlier, the value of bikes[0] is "Herald". Now, the value is changed to "Jawa".
- How to find the size of an Array
var bikes = arrayOf("Herald", "Honda SB Shine", "Bajaj Pulsar 150", "Royal Enfield")
println(bikes.size)
When the user runs the above code, it will the following output:
4
Like other programming languages, Kotlin supports so many functionalities of an array.