Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-dimensional Int array in Kotlin

Tags:

arrays

kotlin

Is it the easiest way to declare two-dimensional Int array with specified size in Kotlin?

val board = Array(n, { IntArray(n) }) 
like image 363
pawegio Avatar asked Dec 16 '14 19:12

pawegio


People also ask

What is int array in Kotlin?

Arrays are used to store multiple values in a single variable, instead of creating separate variables for each value. To create an array, use the arrayOf() function, and place the values in a comma-separated list inside it: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")

How do I create an array of arrays in Kotlin?

There are two ways to define an array in Kotlin. We can use the library function arrayOf() to create an array by passing the values of the elements to the function. Since Array is a class in Kotlin, we can also use the Array constructor to create an array.


1 Answers

Here are source code for new top-level functions to create 2D arrays. When Kotlin is missing something, extend it. Then add YouTrack issues for things you want to suggest and track the status. Although in this case they aren't much shorter than above, at least provides a more obvious naming for what is happening.

public inline fun <reified INNER> array2d(sizeOuter: Int, sizeInner: Int, noinline innerInit: (Int)->INNER): Array<Array<INNER>>      = Array(sizeOuter) { Array<INNER>(sizeInner, innerInit) } public fun array2dOfInt(sizeOuter: Int, sizeInner: Int): Array<IntArray>      = Array(sizeOuter) { IntArray(sizeInner) } public fun array2dOfLong(sizeOuter: Int, sizeInner: Int): Array<LongArray>      = Array(sizeOuter) { LongArray(sizeInner) } public fun array2dOfByte(sizeOuter: Int, sizeInner: Int): Array<ByteArray>      = Array(sizeOuter) { ByteArray(sizeInner) } public fun array2dOfChar(sizeOuter: Int, sizeInner: Int): Array<CharArray>      = Array(sizeOuter) { CharArray(sizeInner) } public fun array2dOfBoolean(sizeOuter: Int, sizeInner: Int): Array<BooleanArray>      = Array(sizeOuter) { BooleanArray(sizeInner) } 

And usage:

public fun foo() {     val someArray = array2d<String?>(100, 10) { null }     val intArray = array2dOfInt(100, 200) } 
like image 108
3 revs, 2 users 74% Avatar answered Oct 03 '22 09:10

3 revs, 2 users 74%