Home » Android » Kotlin: Create a regular array as in Java

Kotlin: Create a regular array as in Java

Posted by: admin November 1, 2017 Leave a comment

Questions:

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.

Answers:

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