https://kotlinlang.org logo
#announcements
Title
# announcements
e

elect

06/12/2019, 9:22 AM
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

diesieben07

06/12/2019, 9:26 AM
Why can't you use
inline
+
reified
exactly?
e

elect

06/12/2019, 9:27 AM
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

diesieben07

06/12/2019, 9:28 AM
You can extend that class as follows:
Copy code
companion object {
  inline operator fun <reified T : Any> invoke() = SteamVR_RingBuffer(T::class)
}
😮 1
e

elect

06/12/2019, 9:28 AM
uh nice
d

diesieben07

06/12/2019, 9:28 AM
Then you can use both the reified "fake constructor" or the normal one
e

elect

06/12/2019, 9:29 AM
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

diesieben07

06/12/2019, 9:39 AM
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

elect

06/12/2019, 9:40 AM
uhm, ok
c

cbruegg

06/12/2019, 9:48 AM
Or just use a list as the buffer?
e

elect

06/12/2019, 9:48 AM
arrays shall be better for performances
c

cbruegg

06/12/2019, 9:49 AM
Sidenote: The standard naming convention would be
SteamVRRingBuffer
e

elect

06/12/2019, 9:49 AM
I know, but it's a port
c

cbruegg

06/12/2019, 9:50 AM
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

elect

06/12/2019, 9:50 AM
no, I always read about it around
c

cbruegg

06/12/2019, 9:50 AM
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
3 Views