Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 255
Bryan Avatar asked Sep 15 '17 18:09

Bryan


1 Answers

Yes, use the constructor of Array:

val buttons = Array(count) { view.findViewById<ImageButton>(BUTTON_IDS[it])!! }
like image 122
hotkey Avatar answered Sep 22 '22 20:09

hotkey