How to create an empty array in kotlin?

I'm using Array(0, {i -> ""}) currently, and I would like to know if there's a better implementation such as Array()

plus, if I'm using arrayOfNulls<String>(0) as Array<String>, the compiler will alert me that this cast can never succeed. But it's the default implementation inside Array(0, {i -> ""}). Do I miss something?


Solution 1:

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>()

Solution 2:

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

var arr = emptyArray<String>()

See

  • doc
  • Array.kt

Solution 3:

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.

Solution 4:

null array

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

Solution 5:

As mentioned above, you can use IntArray(size) or FloatArray(size).