官术网_书友最值得收藏!

Arrays

In Kotlin, arrays are represented by the Array class. To create an array in Kotlin, we can use a number of Kotlin standard library functions. The simplest one is arrayOf():

    val array = arrayOf(1,2,3)   // inferred type Array<Int> 

By default, this function will create an array of boxed Int. If we want to have an array containing Short or Long, then we have to specify the array type explicitly:

    val array2: Array<Short> = arrayOf(1,2,3) 
    val array3: Array<Long> = arrayOf(1,2,3) 

As previously mentioned, using boxed representations may decrease application performance. That's why Kotlin has a few specialized classes representing arrays of primitive types to reduce boxing memory overhead: ShortArray, IntArray, LongArray, and so on. These classes have no inheritance relation to the Array class, although they have the same set of methods and properties. To create instances of this class, we have to use the corresponding factory function:

    val array =  shortArrayOf(1, 2, 3) 
    val array =  intArrayOf(1, 2, 3) 
    val array =  longArrayOf(1, 2, 3) 

It's important to notice and keep in mind this subtle difference, because those methods look similar, but create different type representations:

    val array = arrayOf(1,2,3) // 1 
    val array = longArrayOf(1, 2, 3) // 2 
  1. The generic array of boxed Long elements (inferred type: Array<Long>).
  2. The array containing primitive Long elements (inferred type: LongArray).

Knowing the exact size of an array will often improve performance, so Kotlin has another library function, arrayOfNulls, that creates an array of a given size filled with null elements:

    val array = arrayOfNulls(3) // Prints: [null, null, null] 
    println(array) // Prints: [null, null, null] 

We can also fill a predefined size array using a factory function that takes the array size as the first parameter and a lambda that can return the initial value of each array element given its index as the second parameter:

    val array = Array (5) { it * 2 } 
    println(array) // Prints: [0, 2, 4, 8, 10] 

We will discuss lambdas (anonymous functions) in more detail in Chapter 5, Functions as First Class Citizen. Accessing array elements in Kotlin is done the same way as in Java:

    val array = arrayOf(1,2,3) 
    println(array[1]) //Prints: 2 

Element are also indexed the same way as in Java, meaning the first element has index 0, the second has index 1, and so on. Not everything works the same and there are some differences: the main one is that arrays in Kotlin, unlike in Java, are invariant. We will discuss variance in Chapter 6, Generics Are Your Friends.

主站蜘蛛池模板: 朝阳区| 平谷区| 民丰县| 呼和浩特市| 三原县| 北碚区| 通城县| 张北县| 陇西县| 安岳县| 镶黄旗| 永川市| 右玉县| 苍溪县| 凤山市| 卫辉市| 静海县| 延庆县| 老河口市| 咸宁市| 吴堡县| 瑞安市| 莎车县| 灵丘县| 兴化市| 温州市| 新津县| 呼伦贝尔市| 兴隆县| 绥芬河市| 聊城市| 麻阳| 霍州市| 泰顺县| 天等县| 鹤山市| 华坪县| 云浮市| 崇义县| 河北省| 柯坪县|