How to create an empty array in kotlin?
ArraysKotlinArrays Problem Overview
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?
Arrays Solutions
Solution 1 - Arrays
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 - Arrays
Just for reference, there is also emptyArray
. For example,
var arr = emptyArray<String>()
See
Solution 3 - Arrays
null
? That's the question!
Empty or To create an array of null
s, 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 null
s). E. g. for String
s, 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 - Arrays
null array
var arrayString=Array<String?>(5){null}
var nullArray= arrayOfNulls<String>(5)
Solution 5 - Arrays
As mentioned above, you can use IntArray(size)
or FloatArray(size)
.
Solution 6 - Arrays
I found two ways to create an empty array, the second way without a lambda:
var arr = Array (0, { i -> "" })
var arr2 = array<String>()
Regarding Kotlin's null strings, this is not allowed. You have to use String? type to allow strings to be null.
Solution 7 - Arrays
Use:
@JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
It returns an 0 size array of Strings, initialized with null values.
1. Wrong:
@JvmField val EMPTY_STRING_ARRAY = emptyArray<String>()
It returns arrayOfNulls<String>(0)
2. Wrong:
@JvmField val EMPTY_STRING_ARRAY = arrayOf<String>()
It returns an array containing the Strings.
Solution 8 - Arrays
Simplest way to initialise array and assigning values :
val myArray: Array<String> = Array(2) { "" }
myArray[0] = "Java"
myArray[1] = "Kotlin"