Home > Blockchain >  In Kotlin how Immutable parameters affect space complexity if you have to copy the input every time
In Kotlin how Immutable parameters affect space complexity if you have to copy the input every time

Time:07-03

In Kotlin, function parameters are immutable, so you cannot modify the parameter in the code without making a copy first, does this affect space complexity, and does it prevent in-place modification, thus preventing it from having O(1) constant? What is the solution to this?

fun replaceFirstElement(nums: IntArray, number: Int) {
    // not working
    nums[0] = number
}

CodePudding user response:

An array in Kotlin is always mutable, also when handed over as argument to a function. It is fixed-sized, but the elements are mutable:

fun replaceFirstElement(nums: IntArray, number: Int) {
  nums[0] = number
}

val intArray = IntArray(10) { it   1 }

replaceFirstElement(intArray, 99)

intArray.forEach { println(it) }

Output:

99
2
3
4
5
6
7
8
9
10

This also applies to the other array types, and to the mutable collection like MutableList, MutableMap, etc.

  • Related