IntArray is Kotlin’s specialized array for 32-bit integers. Unlike Array<Int>, it maps to Java’s int[] and stores elements without boxing, making it the practical choice when primitive-array interoperability or storage efficiency matters. section 8.2.5
Create and initialize an IntArray
val fiveZeros = IntArray(5) val fiveZerosToo = intArrayOf(0, 0, 0, 0, 0) val squares = IntArray(5) { i -> (i + 1) * (i + 1) } println(squares.joinToString()) // 1, 4, 9, 16, 25 Use IntArray(size) for default primitive values, intArrayOf(...) for explicit contents, or the size-and-lambda constructor for calculated elements. section 8.2.5
val fiveZeros = IntArray(5) val fiveZerosToo = intArrayOf(0, 0, 0, 0, 0)
Compare the size constructor with intArrayOf using two equivalent arrays of five zero values. section 8.2.5
fun main() {
val squares = IntArray(5) { i -> (i+1) * (i+1) }
println(squares.joinToString())
// 1, 4, 9, 16, 25
}
See a calculated IntArray initialized with consecutive square numbers and printed as a readable sequence. section 8.2.5
Choose the form that matches the data source:
- Convert an existing array or collection of boxed integers with toIntArray(). section 8.2.5
- Prefer collections by default unless primitive-array representation or Java interoperability gives you a reason to use IntArray. section 8.3
