Arrays of Objects and Primitives
We'll cover the following...
We'll cover the following...
The Array<T> class represents an array of values in Kotlin. Use arrays only when low-level optimization is desired; otherwise, use other data structures like List, which we’ll see later in this chapter.
Creating an array in Kotlin
The easiest way to create an array is using the arrayOf() top-level function. Once you create an array, you may access the elements using the index [] operator.
To create an array of Strings, for example, pass the desired values to the arrayOf() function:
Kotlin
val friends = arrayOf("Tintin", "Snowy", "Haddock", "Calculus")println(friends::class) //class kotlin.Arrayprintln(friends.javaClass) //class [Ljava.lang.String;println("${friends[0]} and ${friends[1]}") //Tintin and Snowy
The friends variable holds a reference to the newly created array instance. The type of the object is Kotlin.Array, that is Array<T>, but the underlying real type, ...