2D Array in Kotlin
ArraysKotlinArrays Problem Overview
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);
Arrays Solutions
Solution 1 - Arrays
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 - Arrays
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 - Arrays
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.
Solution 4 - Arrays
I have been using this one-liner when creating matrix
var matrix: Array<IntArray> = Array(height) { IntArray(width) }
Solution 5 - Arrays
1. Nested arrayOf
calls
You can nest calls of arrayOf
, e.g., to create an Array of IntArray
, do the following:
val first: Array<IntArray> = arrayOf(
intArrayOf(2, 4, 6),
intArrayOf(1, 3, 5)
)
Note that the IntArray
itself only takes arguments of type Int
as arguments, so you cannot have an IntArray<IntArray>
which obviously does not make much sense anyway.
2. Use Array::constructor(size: Int, init: (Int) -> T)
for repeated logic
If you want to create your inner arrays with some logical behaviour based on the index, you can make use of the Array
constructor taking a size and an init block:
val second: Array<IntArray> = Array(3) {
intArrayOf(it * 1, it * 2, it * 3, it * 4)
}
//[[0, 0, 0, 0], [1, 2, 3, 4], [2, 4, 6, 8]]
Solution 6 - Arrays
It seems that you are trying to create a ColorStateList
in Kotlin. The code for that is a bit messy, i'll try to keep it readable:
val resolvedColor = Color.rgb(214, 0, 0)
val states = arrayOf(
intArrayOf(-android.R.attr.state_pressed),
intArrayOf(android.R.attr.state_pressed)
)
val csl = ColorStateList(
states,
intArrayOf(resolvedColor, Color.WHITE)
)
Solution 7 - Arrays
You can use a simple 1D (linear) array for this purpose. For example, this is my class for a rectangle array of Double values:
/**
* Rect array of Double values
*/
class DoubleRectArray(private val rows: Int, private val cols: Int) {
private val innerArray: DoubleArray
init {
if(rows < 1) {
throw IllegalArgumentException("Rows value is invalid. It must be greater than 0")
}
if(cols < 1) {
throw IllegalArgumentException("Cols value is invalid. It must be greater than 0")
}
innerArray = DoubleArray(rows*cols)
}
/**
*
*/
fun get(row: Int, col: Int): Double {
checkRowAndCol(row, col)
return innerArray[row*cols + col]
}
/**
*
*/
fun set(row: Int, col: Int, value: Double) {
checkRowAndCol(row, col)
innerArray[row*cols + col] = value
}
/**
*
*/
private fun checkRowAndCol(row: Int, col: Int) {
if(row !in 0 until rows) {
throw ArrayIndexOutOfBoundsException("Row value is invalid. It must be in a 0..${rows-1} interval (inclusive)")
}
if(col !in 0 until cols) {
throw ArrayIndexOutOfBoundsException("Col value is invalid. It must be in a 0..${cols-1} interval (inclusive)")
}
}
}
Solution 8 - Arrays
package helloWorld
import java.util.Scanner
fun main(){
val sc = Scanner(System.`in`)
print("ENTER THE SIZE OF THE ROW: ")
var row = sc.nextInt()
println()
print("ENTER THE SIZE OF COLUMN: ")
val column = sc.nextInt()
println()
var a = Array(row){IntArray(column)}
for(i in 0 until row){
when (i) {
0 -> {
println("----------${i+1} st ROW'S DATA----------")
}
1 -> {
println("----------${i+1} nd ROW'S DATA----------")
}
2 -> {
println("----------${i+1} rd ROW'S DATA----------")
}
else -> {
println("----------${i+1} th ROW'S DATA----------")
}
}
for(j in 0 until column)
{
print("ENTER ${j+1} COLUMN'S DATA: ")
var data:Int = sc.nextInt()
a[i][j]=data;
}
println()
}
println("COLLECTION OF DATA IS COMPLETED")
for(i in 0 until row){
for(j in 0 until column){
print(a[i][j])
print(" ")
}
println()
}
}
It works like this:
Solution 9 - Arrays
Using an inline function and a Pair:
inline fun<reified T> Pair<Int,Int>.createArray(initialValue:T) = Array(this.first){ Array(this.second){initialValue}}
// Create m*n Array of Ints filled with 0
val twoDimArray = Pair(10,20).createArray(0)
// Create m*n Array of Doubles filled with 0.0
val twoDimArray = Pair(10,20).createArray(0.0)
// Create m*n Array of Strings filled with "Value"
val twoDimArray = Pair(10,20).createArray("Value")
...
Solution 10 - Arrays
You can create two one dimensional array and add them in new array.
val unChecked = intArrayOf(-android.R.attr.state_checked)
val checked = intArrayOf(android.R.attr.state_checked)
val states = arrayOf(unChecked, checked)
val thumbColors = intArrayOf(Color.WHITE, Color.parseColor("#55FFD4"))
val stateList = ColorStateList(states, thumbColors)
Solution 11 - Arrays
You can create 2D array in kotlin.
var twoDarray = Array(8) { IntArray(8) }
this is a example of int 2D array