liveBook · Manning

Array

As explained in Kotlin in Action, 2E

An array is an indexed, fixed-size sequence of elements of a specified type.

An array is an indexed, fixed-size sequence whose elements share a specified type. Kotlin provides arrays for cases where Java interoperability or performance makes them appropriate, while collections are generally preferred by default. section 8.0 section 8.3

Read command-line arguments

fun main(args: Array<String>) { for (i in args.indices) { println("Argument $i is: ${args[i]}") } } `Array<String>` declares an array of strings. `indices` supplies its valid indexes, and bracket syntax reads the element at each index.

Create and use arrays in several practical ways:

  • `arrayOf("a", "b")` creates an array from supplied elements; `arrayOfNulls<String>(size)` creates a nullable array filled with nulls. section 8.2.5
  • Use specialized primitive arrays such as `IntArray(5)` or `intArrayOf(0, 0, 0, 0, 0)` when the elements are integers. section 8.2.5
  • Convert a collection with `toTypedArray()` when passing it to a Java array parameter or a Kotlin `vararg` parameter, using the spread operator at the call site. section 8.2.5

Although `Array<Int>` looks generic, its elements are boxed integers on the JVM (`java.lang.Integer[]`). Primitive arrays such as `IntArray` use specialized representations. Kotlin arrays compile to Java arrays, supporting interoperability while retaining Kotlin array syntax. section 8.2.5 section 8.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains array construction, indexing, initialization, collection conversion, boxing, primitive representations, and the preference for collections.
Examples
Demonstrates command-line arguments, alphabet generation, integer squares, primitive-array construction, and collection-to-vararg conversion.
What you can do after
Build and apply typed, nullable, generic, or primitive arrays and pass collections to array-based APIs.
How it connects
Connects arrays with collections, generics, primitive types, nullability, Java interoperability, and vararg parameters.

Also explained in

Compare how 40 books explain array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.