Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Create a regular array as in Java

Tags:

java

kotlin

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.

like image 392
Jire Avatar asked Jun 01 '26 13:06

Jire


1 Answers

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

like image 145
Kirill Rakhman Avatar answered Jun 04 '26 01:06

Kirill Rakhman