How to create an empty array in kotlin?

huangcd picture huangcd · Apr 20, 2015 · Viewed 74.6k times · Source

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?

Answer

Martian Odyssey picture Martian Odyssey · Jun 17, 2015

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