Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty array in kotlin?

Tags:

arrays

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?

like image 337
huangcd Avatar asked Apr 20 '15 08:04

huangcd


People also ask

How do I create an empty list on Kotlin?

To create an empty list in Kotlin, we have two ways. One is using listOf() function and the other is using emptyList() function. where T is the type of elements in this List.

How do I create an array in Kotlin?

There are two ways to define an array in Kotlin. We can use the library function arrayOf() to create an array by passing the values of the elements to the function. Since Array is a class in Kotlin, we can also use the Array constructor to create an array.

How do I set an array list in Kotlin?

The set() function of ArrayList class is used to set the given element at specified index and replace if any element present at specified index. For example: fun main(args: Array<String>){ val arrayList: ArrayList<String> = ArrayList<String>(5)


2 Answers

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>() 
like image 165
Martian Odyssey Avatar answered Oct 16 '22 08:10

Martian Odyssey


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

var arr = emptyArray<String>() 

See

  • doc
  • Array.kt
like image 23
pt2121 Avatar answered Oct 16 '22 10:10

pt2121