On the JVM, it is oftentimes most preferable to use primitive arrays (IntArray, DoubleArray etc.) instead of “normal” arrays (Array, Array etc.) simply because of speed and memory overhead.
For example, on my laptop, reversing 10,000,000 sized Array takes ten times as long as reversing a similar sized DoubleArray.
However, say you want to create something like a new array reverse function, but you want any type of array to work with it. You could create something like:
fun <T> reverse(array: Array<T>) { ... }
However, this only accepts “normal” arrays, not primitive ones.
In fact, since primitive arrays don’t inherit from any other class, the only way to allow all types of primitive arrays in a function is to ask for Any
and throw an exception when a non-primitive array is provided. Or you simply create a function for each type of primitive array (which is exactly what the Kotlin standard library is doing).
I thought that this had to be better, so I created this: GitHub - Jolanrensen/KotlinGenericPrimitiveArrays: Provides a wrapper around all primitive arrays using a sealed interface and value class as to provide a generic way to work with any type of generic array. All the 1.5.10 standard library functions are included as well.
It’s just a proof of concept for now and a lot of the documentation is missing (it’s not even a library, just a kotlin file), but bear with me.
PrimitiveArray<T : Comparable<T>>
is a sealed interface
where the only implementations are the value class
es: PrimitiveDoubleArray
, PrimitiveIntArray
, etc.
Since these implementations are value classes (previously inline classes), you won’t have any object allocation after compile time and since they have one common ancestor, a function can simply ask for a primitive array of any type. These classes (and the interface) have all the functionality of arrays you’d expect and more; I ported over all Kotlin’s Array extension functions to PrimitiveArray
(docs will follow) and since I could make the interface implement anything I wanted, I also made it implement Collection
, this also makes them Iterable
.
Small example:
fun <T : Comparable<T>> reverseArray(array: PrimitiveArray<T>) {...}
val myArray: PrimitiveDoubleArray = doubleArrayOf(1, 2, 3, 4).asPrimitiveArray()
val myOtherArray: PrimitiveBooleanArray = booleanArrayOf(true, false, false, false).asPrimitiveArray()
reverseArray(myArray)
reverseArray(myOtherArray)
It needs to be tested and maybe I’ve missed some functions, so let me know if you find anything that’s missing or if you have any tips!