'Is it possible to set a range of array values in Kotlin?
Let's say I have an array like this:
val grid = Array(10) { IntArray(10) { 1 } }
And now I want to set some of them to 2 instead. I could do this:
for (i in 0..5) {
for (j in 0..5) {
grid[i][j] = 2
}
}
But what I'd like to do is this:
grid[0..5][0..5] = 2
Is there some faster way to do it like this?
Solution 1:[1]
You can achieve something similar, e.g.:
grid[3..5, 2..4] = 5
by using the following extension function:
operator fun Array<IntArray>.set(outerIndices : IntRange, innerIndices : IntRange, newValue : Int) {
for (i in outerIndices) {
for (j in innerIndices) {
this[i][j] = newValue
}
}
}
If you really wanted something like grid[3..5][2..4] = 5 you would then first need to implement a getter for the first IntRange which may hold a ~builder with the actual array reference so that the actual array can be adjusted on the set-call.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roland |
