In this tutorial, we’ll look into Kotlin array. If you’re a new to Kotlin, it’s recommended to go through the Introduction to Kotlin tutorial to ensure that you’re upto speed with this tutorial.
Kotlin Array
Arrays in Kotlin are not native data structure. Instead they’re a class of the type Array
. We can call Kotlin Array as collections class.
Kotlin array declaration – arrayOf function
Following are the different ways we can initialize an Array. To initialize and set the elements of an Array, we use the arrayOf
function.
val countries = arrayOf("India","USA","China","Australia","Sri Lanka")
The Kotlin compiler implicitly defers the type of the Array.
To specify the type we can set the function as :
val countries = arrayOf<String>("India","USA","China","Australia","Sri Lanka") //an array of Strings
A generic array of type Any
can be defined as :
val myArray = arrayOf("Hi",1,1L,1.2,false)
val array1 = arrayOf(1,2,3,4)
val array2 = arrayOf(1L,2L,3L,4L)
val array3 = arrayOf<Long>(1,2,3,4) //this is the same as array2. An array of longs
Accessing and Modifying Elements in Array
Typically, we use the index of the array to access and modify elements of an array. In Kotlin Arrays, we can additionally use get
and set
methods as shown below.
val array1 = arrayOf(1,2,3,4)
val array3 = arrayOf<Long>(1,2,3,4)
array3.get(0)
array3[0]
array1[1] = 6
array1.set(1,6)
println("Size is ${array1.size}") //Size is 4
Note: To get the length of the array, we invoke the function size
Utility Functions for Kotlin Array
Kotlin provides us utility functions to initialise arrays of primitives using functions such as :
charArrayOf()
, booleanArrayOf()
, longArrayOf()
, shortArrayOf()
, byteArrayOf()
.
Using these functions would compile the Array classes into int[]
, char[]
, byte[]
etc.
Additionally, these primitive type arrays are handy when your codebase contains Kotlin as well as Java code. Kotlin type arrays can be passed to the Java code as primitive type arrays. Furthermore, these primitive type arrays boost the performance of the project.
val array1 = intArrayOf(1,2,3,4)
Kotlin Array() Constructor
The constructor expects two parameters. The size
and init
. We specify a lambda expression in the init
parameter as shown below.
val array = Array(6) {i-> i*2}
//or
val array = Array(6,{i-> i*2})
for(element in array)
println(element)
In the above code, the second argument takes in a lambda function, which takes the index of the array element and then returns the value to be inserted at that index in the array.
val array = Array(6) {i-> i*0.1} // Array of Doubles
for(element in array)
println(element)
val array = Array(6) {i-> "Hi "+i}
for(element in array)
println(element)
//prints the following in the console
Hi 0
Hi 1
Hi 2
Hi 3
Hi 4
Hi 5
The compiler would throw an error if an Array Constructor’s size is set but it’s not initialized as shown below.
var intArray = Array(6) //would not compile
var intArray2 : Array<IntArray> //this is fine. Since we've just defined the type of var.
When using a primitive type of Array as shown below, instantiation isn’t necessary, as shown below.
val intArray = IntArray(6)
for(element in intArray)
{
println(element) //all elements are zero here.
}
Allocating the size to a primitive type array will assign all the elements a default value if not instantiated otherwise.
Converting Generic Array to Primitive Array
A generic Array class can be converted into a primitive array type by invoking the method toIntArray()
, toCharArray()
etc on the generic array instance. Following snippet demonstrates the same.
val array1 = arrayOf(1,2,3,4)
var intArray1 : IntArray = array1.toIntArray()
Kotlin Array Examples
Reversing an array
var array1 = arrayOf(1,2,3,4) array1 = array1.reversedArray() for(element in array1) { println(element) } //Prints 4,3,2,1
Reversing an Array in place
var array1 = arrayOf(1,2,3,4) array1.reverse() for(element in array1) { println(element) } //prints 4,3,2,1
Sum of elements of an Array
var array1 = arrayOf(1,2,3,4) println(array1.sum()) //prints 10
Appending an Element in an Array
var array1 = arrayOf(1,2,3,4) array1 = array1.plus(5) //or array1 = array1.plusElement(5) for(element in array1) { println(element) } //prints 1,2,3,4,5
Fill the range of indexes with the given element
var array1 = arrayOf(1,2,3,4) array1.fill(0,0,array1.size) for(element in array1) { println(element) } //prints 0,0,0,0,0
Note: The fill method isn’t constrained to the current size of the array. We can exceed the array’s index limit to increase the length of array too as shown below.
Append an array to the current array
var oldArray = Array(6, {i->i*10}) array1.fill(0,0,array1.size) array1 = array1.plus(oldArray) for(element in array1) { println(element) }
That’s all for kotlin array example, we will use it a lot in further kotlin tutorials and projects.
Reference: Array API Doc
Hi,
can you create some blog related to 2-d array
Sir , I ran one of the above mentioned code which is :
val array = Array(6) {i-> i*0.1} // Array of Doubles
for(element in array)
println(element)
It runs properly but one of the output is not correct( I dont know why). The output which i am getting is :
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
The fourth iteration seems to have some problem as the output should be 0.3 but its showing the above mentioned output. Please help me Sir.