some elegant solution for allocating a not-nullabl...
# announcements
e
some elegant solution for allocating a not-nullable array as buffer for a generic ringBuffer implementation since I cant use inline reified? The only option I see is to pass down as argument the class itself
d
Why can't you use
inline
+
reified
exactly?
e
Copy code
class SteamVR_RingBuffer<T>(clazz: Class<T>, size: Int) {

    protected val buffer = Array(size) {
        clazz.getDeclaredConstructor().newInstance() }
only functions can be reified
d
You can extend that class as follows:
Copy code
companion object {
  inline operator fun <reified T : Any> invoke() = SteamVR_RingBuffer(T::class)
}
😮 1
e
uh nice
d
Then you can use both the reified "fake constructor" or the normal one
e
thanks man
another thing @diesieben07
compiler complains about
T
here
Copy code
class SteamVR_RingBuffer<T : Any>(val clazz: Class<T>, size: Int) {

    val default: T
        get() = clazz.getDeclaredConstructor().newInstance()

    protected val buffer = Array(size) { default }
cant use T as reified parameter, use a class instead
but it doesnt look it accepts
clazz
either
d
Yeah, you probably shouldn't use
Array<T>
. Arrays are weird on the JVM in that
Array<String>
and
Array<Any>
are completely different classes (every element type has it's own class)
You should probably use
Array<Any>
and insert appropriate casts at the appropriate places.
That is what things like
ArrayList
do inside, too.
e
uhm, ok
c
Or just use a list as the buffer?
e
arrays shall be better for performances
c
Sidenote: The standard naming convention would be
SteamVRRingBuffer
e
I know, but it's a port
c
Did you measure whether it actually gives a performance advantage? An
ArrayList
is, as the name implies, backed by an array and should give similar performance.
e
no, I always read about it around
c
The JVM is also pretty good at inlining methods in hot code
I'd just use a list and only if that hurts performance use a raw array