Arrays from Ranges


#1

Is there any better way to get an array from a range?

(0..10).toList().toTypedArray()

Should the Of functions be overloaded to accept ranges?

@Test
fun testSort() {
	val expected = arrayOf(0..10)
	val actual = arrayOf(10 downTo 0)
	sort(actual)
	assertArrayEquals(expected, actual)
}

…seems a lot nicer than:

@Test
fun testSort() {
	val expected = (0..10).toList().toTypedArray()
	val actual = (10 downTo 0).toList().toTypedArray()
	sort(actual)
	assertArrayEquals(expected, actual)
}

I suppose one could want an Array<IntRange>, but that doesn’t seem like the majority use case to me.


#2

I can’t think of a better way using extension functions though, in practice, I’d probably create an array using expressions such as the following rather than use ranges directly:

IntArray(11) { it }            // ascending
IntArray(11) { 10 - it }       // descending

#3

Doesn’t seem that common to want it in the standard library. If it is something you need a lot extension methods like this would do the trick:

fun IntProgression.toArray() =
    IntArray(this.count()).also { forEachIndexed { index, i -> it[index] = i } }

But this will not be as efficient as what @alanfo suggested.

In general I think Kotlin shies away from a lot of operations that result in arrays because arrays are expensive as you have to have all the data vs. a List which is just an interface and can be more lazy.


#4

Another idea might be to support the spread operator for Iterable's, which would save overloading all the collectionOf(...) and arrayOf(...) functions:

@Test
fun testSort() {
	val expected = arrayOf(*0..10)
	val actual = arrayOf(*(10 downTo 0))
	sort(actual)
	assertArrayEquals(expected, actual)
}

#5

I’ve noted this use case here: https://youtrack.jetbrains.com/issue/KT-12663