How to initialize an empty array list in Kotlin?

Kotlin ArrayList class can be used in order to create an empty arrayList. It would be a dynamic array which means it will automatically expand as we add data into it. An ArrayList is an ordered sequence of elements, however, unlike simple arrays, an ArrayList can contain data of multiple data types.

The function definition of arrayList goes like this −

fun <T> arrayListOf(): ArrayList<T>

It returns an empty new ArrayList. If a number is provided as the argument, then it will return an arrayList with the given elements.

Example: Initialize an empty array in Kotlin

The following example demonstrates how you can create a dynamic array list and initialize the same.

fun main(args: Array<String>) {
   val myArrayList = ArrayList<String>()
   println("My Empty ArrayList: " + myArrayList)

   // insert elements in the ArrayList
   println("Elements added in the ArrayList: " + myArrayList)


On execution, it will generate the following output −

My Empty ArrayList: []
Elements added in the ArrayList: [C, Java, SQL, Kotlin]