Arrays of Objects and Primitives
Explore how to create and manipulate arrays of objects and primitive types in Kotlin. Learn to use the arrayOf function, specialized arrays like IntArray, and array methods such as size, average, and sum. Understand when to prefer lists over arrays for flexible, mutable collections.
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:
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, ...