Spread Operator
ID |
kotlin.spread_operator |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
best-practice, performance |
Description
Reports uses of the spread operator (*array) in function call arguments. The spread
operator unpacks an array into a vararg parameter by copying its contents into a new
array at every call site.
Rationale
When you write foo(*array), the compiler emits a call to Arrays.copyOf (or
equivalent) before the actual call to foo. This O(n) copy happens unconditionally —
even if foo only iterates the values once and discards them. For frequently called
paths or large arrays this hidden allocation adds up.
fun sum(vararg n: Int) = n.sum()
val nums = intArrayOf(1, 2, 3)
// Bad
sum(*nums) // copies nums on every call
listOf(*arrayOf(1)) // unnecessary copy
// Good
sum(nums[0], nums[1], nums[2]) // direct — no copy
nums.sum() // purpose-built function — no vararg needed
Prefer:
-
Calling a purpose-built function that accepts a typed collection or array directly (
IntArray.sum(),List.joinToString(), etc.). -
Passing elements directly when the array is small and fixed.
-
Changing the callee signature to accept
IntArray/List<T>instead ofvararg.