Trying to have enums backed by an `IntBuffer`, I'm...
# announcements
e
Trying to have enums backed by an
IntBuffer
, I'm writing an extension function for an Enum, where its companion object extends a specific interface. But if I cast, the compiler says the cast can never succeed.. why?
Copy code
fun <E> Enum<E>.bind() where E : Enum<E>, E : A = (Enum.Companion as B).buffers[ordinal].bind() // this cast can never succeed
s
Also don’t you need to put the return type of the function before the where clause?
e
this fails
Enum.Companion as B
it's
Unit
j
Because that refers to the companion of the
Enum
class, not the companion of the receiver
s
oh I see I misread that
e
is there a way ro retrieve the receiver companion?
r
There is no way in the type system to specify "a class that has a companion object" (let alone of a specific type)
d
A decent compromise is to replace
Enum<E>
with an interface that can return it's "companion object". Won't be type safe but .... it works 😅.
r
Or change
bind
to accept a
B
e
@Dominaezzz problem is that then the buffers would be static per interface. I need to have them per enum. Because I'd like to have the possibility to have multiple enums (extending the same interface) backing each different objects
d
From the interface you decide what object you want to return,
e
can you elaborate @Dominaezzz?
r
That gist has several problems with generics
d
GlBufE
can have a method that returns an instance of
GlBufEco
.
👍 1
e
yeah yeah, it's just a draft
r
Sorry, I only meant I don't understand what each placeholder is supposed to do as the generics don't line up. But I'd go with @Dominaezzz's suggestion if it makes sense (you'd probably have to change the function to
fun <E> E.bind(...
instead of
Enum<E>.bind(...
)
Maybe something like this: https://pl.kotl.in/7LQEa_sRz (Assuming I didn't totally screw up the generics)
d
Tiny upgrade,
T : Enum<T>
.
r
Wouldn't that make
bind
infinitely recursive?
d
Oh nvm. I just had another look at the signature of
bind
.
Should
bind
just be a member at this point.
e
@Ruckus interesting if I write:
fun <T> T.bind(target: BufferTarget) where T : Enum<T>, T : GlBufE = T.buffers[ordinal].bind(target)
I get:
Error:(182, 70) Kotlin: Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left hand side of dot
sorry, I'm an idiot:
fun <T> T.bind(target: BufferTarget) where T : Enum<T>, T : GlBufE = buffers[ordinal].bind(target)
👍 1
@Dominaezzz a member of what?
d
Nvm
👍 1