How can I create an array in Kotlin like in Java by just providing a size?

JavaArraysArraylistKotlin

Java Problem Overview


How can I create a Array like we do in java?

int A[] = new int[N];

How can I do this in Kotlin?

Java Solutions


Solution 1 - Java

According to the reference, arrays are created in the following way:

  • For Java's primitive types there are distinct types IntArray, DoubleArray etc. which store unboxed values.

    They are created with the corresponding constructors and factory functions:

    val arrayOfZeros = IntArray(size) //equivalent in Java: new int[size]
    val numbersFromOne = IntArray(size) { it + 1 }
    val myInts = intArrayOf(1, 1, 2, 3, 5, 8, 13, 21)
    

    The first one is simillar to that in Java, it just creates a primitive array filled with the default value, e.g. zero for Int, false for Boolean.

  • Non primitive-arrays are represented by Array<T> class, where T is the items type.

    T can still be one of types primitive in Java (Int, Boolean,...), but the values inside will be boxed equivalently to Java's Integer, Double and so on.

    Also, T can be both nullable and non-null like String and String?.

    These are created in a similar way:

    val nulls = arrayOfNulls<String>(size) //equivalent in Java: new String[size]
    val strings = Array(size) { "n = $it" } 
    val myStrings = arrayOf("foo", "bar", "baz")
    
    val boxedInts = arrayOfNulls<Int>(size) //equivalent in Java: new Integer[size]
    val boxedZeros = Array(size) { 0 }
    

Solution 2 - Java

Here is simple example of init of Array of String

        var names = Array<String>(<AnotherArray.size>) { i -> "" }

Kotlin doc

Solution 3 - Java

In Kotlin, creating an IntArray of size N is simple. Use IntArray(n) or the appropriate type, as detailed thoroughly in hotkey's answer.

When utilizing your fixed size array, you can use Kotlin Destructuring

// Create fixed sized array
val point = IntArray(2)

// Access values directly
val (x, y) = point

In this case, x will be taken from index 0, y from index 1, etc.

Solution 4 - Java

You can create it using IntArray like this declaration for variable val A = IntArray(N)

Solution 5 - Java

val A = FloatArray(N) //N being the size of the ar

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin MathewView Question on Stackoverflow
Solution 1 - JavahotkeyView Answer on Stackoverflow
Solution 2 - JavaAlexPesView Answer on Stackoverflow
Solution 3 - JavaGiboltView Answer on Stackoverflow
Solution 4 - JavayousefView Answer on Stackoverflow
Solution 5 - JavaVincent Karimi GichimuView Answer on Stackoverflow