Three different ways to create an empty string array in Kotlin

Introduction :

We have a couple of different ways in Kotlin to create one empty string array. Kotlin provides different ways to generate string arrays and we can use them to create one empty string array. In this post, I will show you three different ways to do that with examples.

Using arrayOf :

fun main() {
    val emptyArray = arrayOf<String>()
    print(emptyArray.size)
}

In this example, we are using arrayOf to create one array of Strings but without any initial values. It will create one empty array of size 0 and the program will print 0.

Using Array constructor :

Array constructor is another way to create one empty array. It looks as like below :

fun main() {
    val emptyArray = Array(0){}
    print(emptyArray.size)
}

Same as the above example, it will also print 0.

Using arrayOfNulls :

arrayOfNulls is used to create one array of null values. We can give the size of the array and also type of the array.

fun main() {
    val emptyArray = arrayOfNulls<String>(0)
    print(emptyArray.size)
}

Here, we are creating one array of null that can hold String values and the size of it is 0.

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊