Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!