Kotlin Tutorial: Add New Element to Array

Photo of author

The Kotlin library’s add() method allows us to add an item to an ArrayList.We’ll demonstrate how to create an array of items in Kotlin and add a new item. The “+=” operator or the library utility add() can do this.

This Kotlin lesson will cover a variety of topics, including the basics of arrays, the distinction between a kotlin array and a kotlin intarray, different array operations, including adding elements to lists and appending to arrays, adding elements to mutable and immutable lists, etc.

In almost all programming languages, an array is one of the most basic types of data structures. The concept of an array is to group elements of the same data type, such as strings or integers, under a single variable name. This article examines several Kotlin methods for inserting a new member at the end of an array.

Visit: Kotlin

Basics of Kotlin Arrays

In Kotlin, an array is an entity that denotes a grouping of related objects. It offers predefined attributes and ways to deal with the data in the Array. The arrayOf method or the Array constructor can generate an array.

Kotlin Array Methods and Characteristics

Kotlin arrays offer several practical methods and characteristics for managing data effectively.

See also: Generic Array In Java: Best Practices And Techniques

Several typical characteristics are:

  • size: Returns the Array’s size.
  • indices: Provides a list of all possible indices.

Typical techniques include:

  • get(index): Retrieves the element starting at the given index.
  • set(index, value): Makes the element at the stated index.

Employing Customised Arrays

Specialized classes cover primitive kinds like IntArray, DoubleArray, and other types in Kotlin. These aid in lowering administrative burdens and enhancing efficiency.

Specialized arrays can offer a more specialized API for working with a particular sort of data and can be more memory-efficient.

E.g. Create an array of numbers with the following code:


val intArray = intArrayOf(1, 2, 3)

Create a double array with the following code:


val doubleArray = doubleArrayOf(1.1, 2.2, 3.3)

Kotlin array Vs. Kotlin intarray difference

Kotlin Array and Kotlin IntArray are both used to store items of various data types.

array vs intarray

There are a few distinctions between them, though:

Type

While Array may hold items of any type, IntArray only stores elements of the type integer.

Initialization

You can use the IntArray() constructor or the intArrayOf() function to initialize an IntArray, whereas the Array() constructor or the arrayOf() function can be used to initialize an Array.

Efficiency

Because IntArray was created expressly to hold items of the type integer, it performs better than Array in speed and efficiency.

Syntax

IntArray employs a different syntax than Array for accessing its elements. In an IntArray, we utilize indices to retrieve an element, but in an Array, we use the get() function.

In Kotlin, items are stored in both IntArray and Array. However, IntArray is quicker and more effective for storing integer-type elements, whereas Array may store items of any type.

Read also: Copy Array In JavaScript: Efficient Data Duplication Techniques

Kotlin Add to Array

Introducing something to a Kotlin ArrayList is not difficult because it is virtually identical to the Java array list.

To achieve it, we may use the add() method:


val myArrayList = ArrayList<String>()

myArrayList.add("Tom Hanks")

assertThat(myArrayList).containsExactly("Tom Hanks")

Unsurprisingly, the test succeeds if we run it.

One should mention the fact that Kotlin enables operator overloading. The ‘+=’ operator is also included in the Kotlin standard library to perform the “plusAssign” function on a mutablelist or to add items to the mutable list.

The code may be simpler to comprehend by using the += operator. ‘+=’ can be used, for instance, to add a new item to myArrayList:


myArrayList += "Brad Pitt"

assertThat(myArrayList).containsExactly("Tom Hanks", "Brad Pitt")

Kotlin Add to Array Mutable List

We’ve discovered that invoking the mutableListOf() method will quickly initialize a Kotlin MutableList and produce an ArrayList object. As a result, doing so is precisely the same as inserting a new entry to an ArrayList:


val myMutable = mutableListOf("Tom Hanks", "Brad Pitt")

myMutable.add("Tom Cruise")

assertThat(myMutable).containsExactly("Tom Hanks", "Brad Pitt", "Tom Cruise")

myMutable += "Will Smith"

assertThat(myMutable).containsExactly("Tom Hanks", "Brad Pitt", "Tom Cruise", "Will Smith")

As demonstrated by the test above, we initialize a MutableList with two variables. Then, employing the add() function and the += operator, we use the same procedure to add two members to the list.

If we let the test run, it is successful.

Kotlin Add to Array Read OnlyList

Let’s now examine the Kotlin List type. The list is read-only; thus, we cannot add elements. However, let’s construct a test to see if it holds:


var myList = listOf("Tom Hanks", "Brad Pitt")

myList.add("Tom Cruise")

The compiler issues the following error when compiling the above code: “Kotlin: Unresolved reference: add.” Given that the List interface lacks the add() function, this is to be anticipated.

Let’s check the += operator next:


val myList = listOf("Tom Hanks", "Brad Pitt")

myList += "Tom Cruise"

The code does not compile either, as we had anticipated. This time, though, the error notice reads, “Kotlin: Val cannot be reassigned.”

Let’s now examine this compilation mistake in more detail. First off, since the plusAssign() method is not available for the List interface or its super types, myList += “Tom Cruise” is equivalent to myList = myList + “Tom Cruise”. This clarifies how the reassignment occurs.

Let’s examine the ‘+’ (plus operation) operator for List in more detail:


public operator fun <T> Collection<T>.plus(element: T): List<T> {

val result = ArrayList<T>(size + 1)

result.addAll(this)

result.add(element)

return result

}

The code above demonstrates how Kotlin produces a new List each time we call “List + element” that contains both the original list’s elements and the new element. In other words, the ‘+’ action will result in the creation of a new object.

Next, let’s run a test to confirm it:


var myList = listOf("Tom Hanks", "Brad Pitt")

val originalList = myList

myList += "Tom Cruise"

assertThat(myList).containsExactly("Tom Hanks", "Brad Pitt", "Tom Cruise")

assertThat(myList).isNotSameAs(originalList)

As we can see, we declared the myList variable as changeable by using the var keyword. Additionally, we want to guarantee that the myList variable will correspond to a new object following the execution of myList += “…”.

If we run the test, it is successful.

Read also: Kotlin Array Length: Everything To Know

FAQs

Can Kotlin allow me to delete elements from an array?

Yes, with Kotlin, you may delete elements from a mutable array using methods like remove(), removeAt(), or removeAll().

What steps should I take in Kotlin if I'd like to add an item to the starting point of an array?

With an index of 0, you may use the add(index, element) function to add an element to the start of a flexible array.

Can I add items to a Kotlin immutable array?

Once generated, immutable arrays cannot be changed. However, you may use operations like plus() to build another array based on the old Array with more entries.

Conclusion

We have covered a wide range of efficient and effective methods for adding elements to arrays in this in-depth Kotlin lesson. Kotlin provides adaptable ways to tackle this typical programming problem, whether you’re dealing with mutable or immutable arrays.

You are prepared to take on various Kotlin programming tasks once you have mastered the “kotlin add to array” techniques taught in this course. Coding is fun!

Check this out: Array Vs ArrayList In Java: Which One To Choose And Why?

Leave a Comment