Lab 6.1: Arrays in Kotlin
In this lab you are going to experiment with Arrays. You will need to use IntelliJ IDE.
- Create a new project and Select Kotlin and tick the Sample Code check box.
-
Modify the
Main.kt
content so it looks like: -
Inside the
main(..){
...}
we are going to declare and initialise three arrays,intArray
,stringArray
, anddoubleArray
: -
To output these arrays we are going to use
joinToString()
println("intArray: ${intArray.joinToString()}") println("stringArray: ${stringArray.joinToString()}") println("doubleArray: ${doubleArray.joinToString()}")
- The
joinToString()
function is used to convert arrays into strings for display.
- The
-
Now let's access the first and second index of
intArray
andstringArray
respectively. Add the following underneath the last block of code:println("First element of intArray: ${intArray[0]}") println("Second element of stringArray: ${stringArray[1]}")
- Remember the array[index] points to the position of a value whose index starts from 0 to size of the array - 1.
- Try and get the last element from both arrays.
-
We can iterate of an array using a for loop. Continuing underneath the last code added:
println("Iterating through intArray, using object:") for (element in intArray) { println(element) }
- the
element
is like an object in a toy box.
- the
-
Continuing with looping we can setup the for loop differently, repeat:
-
We can modify and array when the array is mutable as in it is a
var
not aval
. Modify the third element ofintArray
by setting it to 10 and then print the modifiedintArray
: -
We create a two-dimensional array (
twoDArray
) and populate it with values. We then iterate through the two-dimensional array and print its contents.val twoDArray = Array(3) { IntArray(4) } // 3x4 matrix for (i in 0 until 3) { for (j in 0 until 4) { twoDArray[i][j] = i + j } }
-
Now define a custom data class
Person
and create an array ofPerson
objects (personArray
). We iterate throughpersonArray
and print the name and age of each person:data class Person(val name: String, val age: Int) val personArray = arrayOf( Person("Aiya", 28), Person("Bobi", 22), Person("Charlie", 35) ) println("Array of Persons:") for (person in personArray) { println("Name: ${person.name}, Age: ${person.age}") }