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

504
Views
How to initialize Kotlin IntArray from IntRange?

I'm trying to initialize an IntArray in Kotlin like so:

intArrayOf(1..9)

But I get a TypeError that Int is required, but I'm providing an IntRange. Is there a way to initialize the array with a range, or do I have to explicitly write out each value?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Using built in functions, this is how you could get to an IntArray from an IntRange:

val array: IntArray = (1..9).toList().toIntArray()

This is a bit wasteful, because it first constructs a list where it puts all the elements, and then it constructs an array as well. To do this directly, you could use your own extension, something like...

fun IntRange.toIntArray(): IntArray {
    if (last < first)
        return IntArray(0)

    val result = IntArray(last - first + 1)
    var index = 0
    for (element in this)
        result[index++] = element
    return result
}

Which would give you this syntax:

val array: IntArray = (1..9).toIntArray()
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!