Jire
Jire

Reputation: 10280

Kotlin: Create a regular array as in Java

For example, in Java I can create such an array with this syntax:

Thing box = new Thing[10];

In Kotlin such syntax can't be used. I would like to create the equivalent of above in Kotlin.

I have found the Array(size: Int, init: Int -> T) methods but it requires that I specify an init lambda that will not allow me to use null. I want to have an array filled with null or some equivalent of the size that I want.

The scenario: I need to have an array of packet handlers where the index of the handler is the packet's opcode.

Upvotes: 3

Views: 1366

Answers (1)

Kirill Rakhman
Kirill Rakhman

Reputation: 43811

Use arrayOfNulls(). Naturally, your array will be of nullable type. Alternatively, just use a list.

Upvotes: 13

Related Questions