How to create an empty array in kotlin?

Empty or null? That's the question!

To create an array of nulls, simply use arrayOfNulls<Type>(length).


But to generate an EMPTY array of size length, use:

val arr = Array(length) { emptyObject }

Note that you must define an emptyObject properly per each data-type (beacause you don't want nulls). E. g. for Strings, emptyObject can be "". So:

val arr = Array(3) { "" }  // is equivalent for: arrayOf("","","")

Here is a live example. Note that the program runs with two sample arguments, by default.


As of late (June 2015) there is the Kotlin standard library function

public fun <T> arrayOf(vararg t: T): Array<T>

So to create an empty array of Strings you can write

val emptyStringArray = arrayOf<String>()

Just for reference, there is also emptyArray. For example,

var arr = emptyArray<String>()

See

  • doc
  • Array.kt

null array

var arrayString=Array<String?>(5){null}
var nullArray= arrayOfNulls<String>(5)

Tags:

Arrays

Kotlin