Arrays in Kotlin


In majority of programming languages, an array can be defined as a data structure that contains collection of elements of the same data type. Now in Kotlin replace that same with any. This is very unique in that Kotlin is a statically typed language like Java and C#, however it's arrays are as flexible as those of dynamic languages like Python and Ruby.

EXAMPLE

//class definition
class OurKotlinArray {
    fun showArrayData()
    {
        val arrayData = arrayOf(1,"Challenger","Apollo",2.5,'c',true,false)
        println("ARRAY WITH MULTIPLE DATA TYPES")
        println(arrayData.joinToString ("\n"))
    }
}

//main method
fun main(args: Array<String>) {
    OurKotlinArray().showArrayData()
}

RESULT

ARRAY WITH MULTIPLE DATA TYPES
1
Challenger
Apollo
2.5
c
true
false

NOTE: We are using the joinToString() method to Create a string from all the elements separated using separator.You can also supply a prefix and postfix. Our separator in this case is the new line operator("\n").

In Kotlin Arrays belong to a class Array. This class has a get and set functions and a size property alongside other functions that can be used to manipulate it.

class Array<T> private constructor() {
    val size: Int
    operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit
    operator fun iterator(): Iterator<T>
// ...
}

Creating Arrays

There are three main ways of creating an array in kotlin:

  1. Use the function arrayOf(). Pass it the elements. For example arrayOf(1,2,3,4) will create an array [1,2,3,4].
  2. You can also use the arrayOfNulls() function to create an array of a given size filled with null values.
  3. Use a factory function that takes the array size and the function that can return the initial value of each array element given its index:
// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5, { i -> (i * i).toString() })

There are also specialized classes in Kotlin to represent arrays of primitive types without boxing overhead. These include:

  1. ByteArray.
  2. ShortArray.
  3. IntArray etc.
val x: IntArray = intArrayOf(1, 2, 3)
x[0] = x[1] + x[2]

Examples

1. Functional arrayOf() Example with integers

fun main(args: Array<String>) {
    val availableApartments = arrayOf(2,6,9,12,29)
    println("AVAIALABLE APARTMENTS")
    println(availableApartments.joinToString (" \n"))
}

RESULTS

AVAIALABLE APARTMENTS
2
6
9
12
29

2. Object Oriented arrayOf() Example with integers


class ApartmentManager {
    fun showAvailableApartments()
    {
        val availableApartments = arrayOf(2,6,9,12,29)
        println("AVAIALABLE APARTMENTS")
        println(availableApartments.joinToString ("\n"))
    }
}

fun main(args: Array<String>) {
    ApartmentManager().showAvailableApartments()
}

RESULTS

AVAIALABLE APARTMENTS
2
6
9
12
29

3.Object Oriented arrayOf() example with strings

//class definition
class SpacecraftsManager {
    fun showSpacecrafts()
    {
        val planetarySpacecrafts = arrayOf("Columbia","Challenger","Apollo","Enterprise","Endeavor","Atlantis")
        println("INTERPLANETARY SPACECRAFTS")
        println(planetarySpacecrafts.joinToString ("\n"))
    }
}

//main method
fun main(args: Array<String>) {
    SpacecraftsManager().showSpacecrafts()
}

RESULT

INTERPLANETARY SPACECRAFTS
Columbia
Challenger
Apollo
Enterprise
Endeavor
Atlantis

4.Object Oriented arrayOfNulls() Example

You can use arrayOfNulls(size) to create an array of null values. You pass in the generic type represented by T. Size is passed as a parameter.

//class definition
class SpacecraftsManager {

    fun showGalacticShips()
    {
        val galacticShips=arrayOfNulls<String>(5);
        println(galacticShips.joinToString ("\n"))

    }
}

//main method
fun main(args: Array<String>) {
    SpacecraftsManager().showGalacticShips()
}

RESULT

null
null
null
null
null

5. ArrayOf Data Objects/Value Objects

Let's say you have 5 planet objects(reference types) and you want to work with them in an array and print them out.

//class definition
class Planet(val name: String) {
    override fun toString(): String {
        return name
    }
}
//main method
fun main(args: Array<String>) {
    val planets=arrayOf(Planet("Mercury"),Planet("Venus"),Planet("Earth"),Planet("Mars"),Planet("Jupiter"))
    println(planets.joinToString("\n"))
}

RESULT

Mercury
Venus
Earth
Mars
Jupiter

6. Array Of Distinct Custom Objects

Kotlin arrays can take multiple objects of distinct types. Say for example a single array that has Planet Object, Star Object and Galaxy object.

class Planet(val name: String) {
    override fun toString(): String {
        return name
    }
}
class Star(val name: String) {
    override fun toString(): String {
        return name
    }
}
class Galaxy(val name: String) {
    override fun toString(): String {
        return name
    }
}
//main method
fun main(args: Array<String>) {
    val planets=arrayOf(Planet("Earth"),Star("Sun"),Galaxy("Milky way"))
    println(planets.joinToString("\n"))
}

RESULT

Earth
Sun
Milky way

7. Get a single Element From an Array

You can obtain a given element from an array as long as you know it's position. We then use the get() method of the Array class.
e.g

galaxies.get(1)

EXAMPLE

class Galaxy(val name: String) {
    override fun toString(): String {
        return name
    }
}
//main method
fun main(args: Array<String>) {
    val galaxies=arrayOf(Galaxy("Andromeda"),Galaxy("Milky Way"),Galaxy("Sombrero"),Galaxy("Leo"))
    println(galaxies.get(1))
}

RESULT

Milky Way

8. Replace a given element in an array.

You can replace an element in an array using the set() method. You pass the target index and the new value in the parameter.
e.g

galaxies.set(3,Galaxy("Whirlpool"))

EXAMPLE

class Galaxy(val name: String) {
    override fun toString(): String {
        return name
    }
}
//insert an element int an array
fun main(args: Array<String>) {
    val galaxies=arrayOf(Galaxy("Andromeda"),Galaxy("Milky way"),Galaxy("Sombrero"),Galaxy("Leo"))
    galaxies.set(3,Galaxy("Whirlpool"))
    println(galaxies.joinToString(","))
}

RESULT

Andromeda,Milky way,Sombrero,Whirlpool

9. Add an Element into an Existing Array.

We can add an element into an array using plusElement() and return a new collection containing the original array plus the added element.
e.g

val updatedGalaxies =galaxies.plusElement(Galaxy("Cartwheel"))

EXAMPLE

class Galaxy(val name: String) {
    override fun toString(): String {
        return name
    }
}
//insert an element int an array
fun main(args: Array<String>) {
    val galaxies=arrayOf(Galaxy("Andromeda"),Galaxy("Milky way"),Galaxy("Sombrero"),Galaxy("Leo"))

    val updatedGalaxies =galaxies.plusElement(Galaxy("Cartwheel"))
    println(updatedGalaxies.joinToString("\n"))
}

RESULT

Andromeda
Milky way
Sombrero
Leo
Cartwheel

10. Combine two Arrays into one

You can combine two arrays into a single array using the plus() method. Let's combine two arrays and then print out the elements of the resulting array.
e.g

val combinedGalaxies =nearbyGalaxies.plus(farwayGalaxies)

EXAMPLE

class Galaxy(val name: String) {
    override fun toString(): String {
        return name
    }
}
//combine two arrays
fun main(args: Array<String>) {
    val nearbyGalaxies=arrayOf(Galaxy("Andromeda"),Galaxy("Milky way"),Galaxy("Sombrero"),Galaxy("Leo"))
    val farwayGalaxies=arrayOf(Galaxy("StarBust"),Galaxy("Centaurus A"),Galaxy("Virgo Stellar stream"),Galaxy("Hoag's Object"))

    val combinedGalaxies =nearbyGalaxies.plus(farwayGalaxies)
    println(combinedGalaxies.joinToString("\n"))
}

RESULT

Andromeda
Milky way
Sombrero
Leo
StarBust
Centaurus A
Virgo Stellar stream
Hoag's Object

11. Get a copy of an Array

You can obtain a copy of an array using the copyOf() method.
e.g

val copyOfTowns =towns.copyOf()

EXAMPLE

class Town(val name: String) {
    override fun toString(): String {
        return name
    }
}
//combine two arrays
fun main(args: Array<String>) {
    val towns=arrayOf(Town("New York"),Town("Nairobi"),Town("London"),Town("New Delhi"))

    val copyOfTowns =towns.copyOf()
    println(copyOfTowns.joinToString(","))
}

RESULT

New York,Nairobi,London,New Delhi

12. Copy a Given Range from an array.

Say you want to copy only a given range of values from an array. You can use the copyOfRange() method. You pass two integer parameters:

  • fromIndex
  • toIndex

e.g

val europeanTowns =towns.copyOfRange(3,7)

EXAMPLE

class Town(val name: String) {
    override fun toString(): String {
        return name
    }
}
//copy range from array
fun main(args: Array<String>) {
    val towns=arrayOf(Town("New York"),Town("Nairobi"),Town("New Delhi"),Town("London"),Town("Paris"),Town("Madrid"),Town("Paris"),Town("Buenos Aires"))

    //pass fromIndex and toIndex
    val europeanTowns =towns.copyOfRange(3,7)
    println(europeanTowns.joinToString(","))
}

RESULT

London,Paris,Madrid,Paris

Check how to populate a JavaFX ListView from an array here.

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post