How to create an empty array in Kotlin? Examples with intArrayOf, arrayOf and Array()
Hello colleagues! I recently started learning Kotlin after Java and encountered a small but important problem. I need to create an empty array so that I can dynamically add elements to it later (or at least initialize it in advance).
In Java I used to do this:
```java
int[] arr = new int[0];
String[] arr2 = new String[0];
```
But in Kotlin I got confused. I tried writing:
```kotlin
val arr = arrayOf() // Error: Cannot infer type
var list = intArrayOf() // Seems to work, but what type?
```
The compiler complains if I don't specify the type. And what if I want an array of strings or custom objects? I also read about `Array(0) {...}`, but I don't understand how to use it correctly.
The main task: create an empty array (for example, for Int, String, or my own class) so that I can later assign it
No answers yet.
Log in to leave an answer
Blogs
How to Write a REST API in Rust in 30 Minutes: A Step-by-Step Guide
Generics in PHP: Why They Are Needed and How to Use Them