Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

int A[] = new int[N]; 

How can I do this in Kotlin?

like image 936
Kevin Mathew Avatar asked Feb 07 '16 12:02

Kevin Mathew


People also ask

How do you declare an array of a certain size in Java?

To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets. String arrayName[] = new String[size]; //or String[] arrayName = new String[size];

How do I declare a fixed size array in Kotlin?

In Kotlin, creating an IntArray of size N is simple. Use IntArray(n) or the appropriate type, as detailed thoroughly in hotkey's answer. In this case, x will be taken from index 0, y from index 1, etc.

How do I create an array 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.


2 Answers

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 } 
like image 91
hotkey Avatar answered Sep 25 '22 23:09

hotkey


Here is simple example of init of Array of String

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

Kotlin doc

like image 29
AlexPes Avatar answered Sep 22 '22 23:09

AlexPes