Generic Array Of Primitives

ID

kotlin.generic_array_primitives

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

best-practice, performance

Description

Reports type references of the form Array<Int>, Array<Long>, and similar where the element type is a Kotlin primitive. Kotlin provides specialized array types (IntArray, LongArray, etc.) that store values without boxing.

Rationale

Array<Int> is backed by Integer[] on the JVM — each element is a boxed Integer object. IntArray is backed by int[] — primitive, unboxed, much smaller in memory, and faster to access. The generic form should only be used when the nullability of individual elements is required (Array<Int?>) or when the code must interoperate with a generic algorithm that cannot accept IntArray.

// Bad
val ids: Array<Int> = arrayOf(1, 2, 3)
fun sum(values: Array<Long>): Long = values.sum()

// Good
val ids: IntArray = intArrayOf(1, 2, 3)
fun sum(values: LongArray): Long = values.sum()

The corresponding conversions are:

Avoid

Prefer

Array<Int>

IntArray

Array<Long>

LongArray

Array<Short>

ShortArray

Array<Byte>

ByteArray

Array<Float>

FloatArray

Array<Double>

DoubleArray

Array<Char>

CharArray

Array<Boolean>

BooleanArray

Remediation

Replace Array<T> with the specialized TArray type and update the corresponding constructor call (arrayOf(…​)intArrayOf(…​), etc.).