...

/

Arrays of Objects and Primitives

Arrays of Objects and Primitives

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:

Press + to interact
val friends = arrayOf("Tintin", "Snowy", "Haddock", "Calculus")
println(friends::class) //class kotlin.Array
println(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, ...