elect
elect

Reputation: 7190

Kotlin, casting function receiver

I have a couple objects, such as object Buffer, offering determined functions and I'd like to call

binding(bufferName[Buffer.VERTEX] to GL_ARRAY_BUFFER) {
    ... // calling Buffer functions
}

where inside I have available, for example, the functions of the object Buffer because of the GL_ARRAY_BUFFER

binding is at the moment so defined

inline fun <T, R> binding(pair: Pair<Int, Int>, block: T.() -> R)

So my question is if it's possible "casting" T to a specific object based on pair.second so that I can call those functions that the object offers?

Upvotes: 0

Views: 564

Answers (1)

pdpi
pdpi

Reputation: 4233

Choosing T depending on the Int value pair.second is not, to the best of my knowledge, possible. However, sealed classes are a good way to implement this sort of "enum with different methods for each value" kind of logic:

sealed class BufferType(val type: Int) {
    class ArrayBuffer() : BufferType(GL_ARRAY_BUFFER)
    class AtomicCounterBuffer() : BufferType(GL_ATOMIC_COUNTER_BUFFER)
    /* other buffer types... */
}

inline fun <Buffer: BufferType, R> binding(pair: Pair<Int,Buffer>, block : (Buffer) -> R) {
    glBindBuffer(pair.second.type, pair.first)
    block()
    /* ... */
}

Then you can expose all the available buffer methods on either the top level BufferType class (for globally available methods), or each individual buffer type.

Upvotes: 1

Related Questions