liveBook · Manning

Boxing

As explained in Kotlin in Action, 2E

Boxing is the representation of a primitive value as an object instance such as java.lang.Integer.

Boxing represents a primitive value as an object. In Kotlin, a generic Array<Int> becomes a Java java.lang.Integer[] and stores boxed integers. section 8.2.5

Choose the array type according to interoperability and storage needs:

  • Use Array<Int> when an object array is required, such as when calling Java APIs that expect object arrays. section 8.2.5
  • Use IntArray to compile to a Java int[] and avoid boxing, storing values in the primitive representation. section 8.2.5
  • Create primitive arrays with IntArray(size), intArrayOf(...), or an initialization lambda. section 8.2.5

Boxed versus primitive arrays

val boxed = Array<Int>(3) { it } val unboxed = IntArray(3) { it } The first declaration produces boxed integers; the second produces a primitive int[] representation. section 8.2.5

val fiveZeros = IntArray(5)
val fiveZerosToo = intArrayOf(0, 0, 0, 0, 0)

Compare two concise ways to create an IntArray without boxing. section 8.2.5

How Kotlin in Action, 2E covers it

How deep it goes
Distinguishes boxed and primitive array representations, then stops short of broader boxing rules outside arrays.
Examples
Uses Array<Int>, IntArray, intArrayOf, and zero-filled primitive-array examples.
What it assumes
Assumes familiarity with Kotlin arrays and distinguishes generic object arrays from specialized primitive-array classes.
What you can do after
Apply it by selecting Array<Int> for object-array compatibility or IntArray for unboxed primitive storage.
How it connects
Connects boxing with arrays, primitive types, Java interoperability, vararg parameters, and performance.

Also explained in

Compare how 3 books explain boxing →

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.