Is there a way to create a nonzero array from a range?

In Java, a simple array can be created using the 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 gives the following:

val buttons = arrayOfNulls<ImageButton>(count)

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

The problem is that now each element of the array is optional; which makes up my code with operators ?.

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

+4
source share
1 answer

Yes, use the constructor Array:

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

Source: https://habr.com/ru/post/1685772/


All Articles