0

Is there a way to initialize an array in Kotlin in this way with a range and mixed numbers.

intArrayOf(4, 10, 3, 20..24)

The contents of the array should be [4, 10, 3, 20, 21, 22, 23, 24]

3
  • 1
    Does this answer your question? How to fill varargs with range? Commented Jan 16, 2020 at 22:26
  • 20..24 have type intRange, so you should firstly convert type intRange to Int type. I think you making some kind of bicycle bro ). Commented Jan 16, 2020 at 22:36
  • Marvin I found something that let me do it like this intArrayOf(4, 10, 3) + IntArray(5) { 20 + it } but then I would have to count the number of elements in the range and put it as the size every time. Commented Jan 16, 2020 at 22:44

2 Answers 2

2
intArrayOf(4, 10, 3, *((20..24).toList().toIntArray()))
Sign up to request clarification or add additional context in comments.

Comments

0

Following the answer by @ardenit, you can make it a bit more appealing like so:

fun IntRange.arr() = this.toList().toIntArray()

fun main() {
    intArrayOf(4, 10 , *(20..24).arr(), *(90 until 95).arr()) // [4, 10, 20, 21, 22, 23, 24, 90, 91, 92, 93, 94]

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.