Search code examples
arrayskotlinkotlin-null-safety

Is there a way to create a non-null array from a range?


In Java a simple array can be created by using a traditional for loop:

ImageButton[] buttons = new ImageButton[count];

for (int i = 0; i < count; i++) {
   buttons[i] = view.findViewById(BUTTON_IDS[i]);
}

A simple conversion to Kotlin yields the following:

val buttons = arrayOfNulls<ImageButton>(count)

for (i in 0..count) {
    buttons[i] = view.findViewById<ImageButton>(BUTTON_IDS[i])
}

The issue with this is that now each element in the array is optional; which riddles my code with ? operators.

Is there a way to create an array in a similar manner, but without the optional type?


Solution

  • Yes, use the constructor of Array:

    val buttons = Array(count) { view.findViewById<ImageButton>(BUTTON_IDS[it])!! }