Make extensions for kotlin arrays I wanted to make a library thing which provides specific extensions for collections/collection-like containers in kotlin:

fun &lt;T&gt; Collection&lt;T&gt;.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }

fun String.extendEntries(length: Int) = this.toList().extendEntries(length)
fun &lt;T&gt; Array&lt;T&gt;.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun CharArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun BooleanArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun DoubleArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun IntArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun LongArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun FloatArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun ByteArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }
fun ShortArray.extendEntries(length: Int) = this.flatMap { x -&gt; List(length) { x } }


Is the above a good way to do it if I want to cover arrays?

Exampe usage:


val a = intArrayOf(1, 2, 3)
println(a.extendEntries(5))



Outputs:


[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Sadly, yes. If you want users of your library to write intArrayOf(1, 2, 3).extendEntries(5) then this is how it is done in Kotlin.

In fact, the Kotlin source code contains methods similar to it, with a specific function for each type of array: (kotlin.collections._Arrays.kt)

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun &lt;R&gt; ShortArray.flatMap(transform: (Short) -&gt; Iterable&lt;R&gt;): List&lt;R&gt; {
    return flatMapTo(ArrayList&lt;R&gt;(), transform)
}

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun &lt;R&gt; IntArray.flatMap(transform: (Int) -&gt; Iterable&lt;R&gt;): List&lt;R&gt; {
    return flatMapTo(ArrayList&lt;R&gt;(), transform)
}

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original array.
 */
public inline fun &lt;R&gt; LongArray.flatMap(transform: (Long) -&gt; Iterable&lt;R&gt;): List&lt;R&gt; {
    return flatMapTo(ArrayList&lt;R&gt;(), transform)
}


However, Kotlin uses a generator to generate such files, see the README at https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib

In your case, you might consider just implementing Iterable&lt;T&gt;.extendEntries as all of these specific types of arrays can be transformed to an Iterable&lt;T&gt; using the Kotlin stdlib .asIterable function.