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

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.

主站蜘蛛池模板: 洮南市| 成都市| 菏泽市| 山阴县| 辉县市| 白玉县| 弥渡县| 吉木萨尔县| 郓城县| 翁牛特旗| 响水县| 新蔡县| 岳西县| 鄂托克前旗| 怀柔区| 连州市| 乌拉特中旗| 西乡县| 淅川县| 彭水| 北碚区| 固原市| 崇仁县| 滦南县| 枝江市| 阳东县| 名山县| 吕梁市| 郓城县| 远安县| 北海市| 黄石市| 安化县| 龙州县| 忻城县| 太康县| 石家庄市| 芜湖市| 凌海市| 余江县| 凤台县|