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

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.

主站蜘蛛池模板: 夏津县| 沾益县| 灵川县| 津南区| 庄河市| 巴里| 靖安县| 合阳县| 安宁市| 巴中市| 巴中市| 凤凰县| 桂东县| 阳东县| 东乡县| 鸡泽县| 阳城县| 温泉县| 新田县| 屏东市| 任丘市| 甘谷县| 蒙阴县| 曲周县| 永宁县| 龙川县| 南和县| 沂水县| 富宁县| 张家口市| 昌宁县| 都兰县| 靖州| 白山市| 岑巩县| 商都县| 玉树县| 哈尔滨市| 双牌县| 荥阳市| 余干县|