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

前端 未结 2 1320
旧巷少年郎
旧巷少年郎 2020-12-04 20:48

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

int A[] = new int[N];

How can I do this in Kotlin?

2条回答
  •  青春惊慌失措
    2020-12-04 21:18

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

提交回复
热议问题