2D Array in Kotlin
How do you make a 2D Int array in Kotlin? I'm trying to convert this code to Kotlin:
int[][] states = new int[][] {
new int[]{-android.R.attr.state_pressed}, // not pressed
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
foregroundColor,
accentColor,
accentColor
};
ColorStateList myList = new ColorStateList(states, colors);
Here is one attempt I tried, where the first 2D array didn't work, but I got the 1D array to work:
//This doesn't work:
var states: IntArray = intArrayOf(
intArrayOf(-android.R.attr.state_pressed), // not pressed
intArrayOf(android.R.attr.state_pressed) // pressed
);
//This array works:
var colors: IntArray = intArrayOf(
foregroundColor,
accentColor,
accentColor
);
val myList: ColorStateList = ColorStateList(states, colors);
Solution 1:
You may use this line of code for an Integer array.
val array = Array(row) { IntArray(column) }
This line of code is pretty simple and works like 1D array and also can be accessible like java 2D array.
Solution 2:
You are trying to put your IntArrays inside another array to make it 2-dimensional.
The type of that array cannot be intArray, which is why this fails.
Wrap your initial arrays with arrayOf
instead of intArrayOf
.
val even: IntArray = intArrayOf(2, 4, 6)
val odd: IntArray = intArrayOf(1, 3, 5)
val lala: Array<IntArray> = arrayOf(even, odd)
Solution 3:
Short Answer:
// A 6x5 array of Int, all set to 0.
var m = Array(6) {Array(5) {0} }
Here is another example with more details on what is going on:
// a 6x5 Int array initialise all to 0
var m = Array(6, {i -> Array(5, {j -> 0})})
The first parameter is the size, the second lambda method is for initialisation.