Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Array in Kotlin

Tags:

arrays

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); 
like image 830
Rock Lee Avatar asked Dec 07 '15 23:12

Rock Lee


People also ask

What is two dimensional array in Kotlin?

This article explores different ways to print two-dimensional arrays in Kotlin. A two-dimensional array is a single-dimensional array having another single-dimensional array as its elements.

What are arrays in Kotlin?

Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value.


1 Answers

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.

like image 196
HM Nayem Avatar answered Sep 29 '22 16:09

HM Nayem