Kotlin 科特林,投射功能接收器

Kotlin 科特林,投射功能接收器,kotlin,Kotlin,我有几个对象,比如对象缓冲区,提供确定的函数,我想调用 binding(bufferName[Buffer.VERTEX] to GL_ARRAY_BUFFER) { ... // calling Buffer functions } 例如,由于GL\u ARRAY\u Buffer 绑定目前是这样定义的 inline fun <T, R> binding(pair: Pair<Int, Int>, block: T.() -> R) inlinefun

我有几个
对象
,比如
对象缓冲区
,提供确定的函数,我想调用

binding(bufferName[Buffer.VERTEX] to GL_ARRAY_BUFFER) {
    ... // calling Buffer functions
}
例如,由于
GL\u ARRAY\u Buffer

绑定
目前是这样定义的

inline fun <T, R> binding(pair: Pair<Int, Int>, block: T.() -> R)
inlinefun绑定(对:对,块:T.()->R)

所以我的问题是,是否可以基于pair.second将T“强制转换”到特定对象,以便调用该对象提供的函数?

根据Int值
对选择T。就我所知,second
不可能。但是,密封类是实现这种“针对每个值使用不同方法的枚举”逻辑的好方法:

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()
    /* ... */
}
密封类缓冲类型(val类型:Int){
类ArrayBuffer():BufferType(GL\U数组\U缓冲区)
类AtomicCounterBuffer():BufferType(GL\u原子计数器\u缓冲区)
/*其他缓冲区类型*/
}
内联绑定(对:对,块:(缓冲区)->R){
glBindBuffer(pair.second.type,pair.first)
块()
/* ... */
}

然后,您可以在顶级
BufferType
类(对于全局可用的方法)或每个单独的缓冲区类型上公开所有可用的缓冲区方法。

在这种情况下,Kotlin不强制您指定函数泛型类型,使该类型在块体中可用吗?绑定(..){//“this”上可用的缓冲区方法}