I don't suppose there's a way to abstract the decl...
# getting-started
r
I don't suppose there's a way to abstract the declaration of the fields on an anonymous object is there?
Context - I'm declaring CTEs using jOOQ using anonymous objects like this:
Ideally it'd look like this:
But that implies that the lambda passed to
cte
actually creates the fields on the anonymous object, which I imagine is impossible?
y
I'm guessing the part you don't want is the
getDialect(), "RESULT_OF_A_QUERY")
right?
r
Yes, primarily - I'd like to use
by
delegation to deduce the string from the property name
y
Your only chance I think is if Jooq Tables can be modified after creation. I'm not familiar with them but I can imagine that they're immutable?
r
It's my class, I could make it mutable...
y
Great. On mobile so it took me a bit to write this, but it compiles:
Copy code
import kotlin.reflect.*
open class JooqTable(var name: String = "")

operator fun <T: JooqTable> T.provideDelegate(thisRef: Any?, prop: KProperty<*>): T {
    this.name = prop.name
    return this
}
operator fun <T: JooqTable> T.getValue(thisRef: Any?, prop: KProperty<*>): T {
    return this
}
fun main() {
    val MY_TABLE by object: JooqTable() {
        val myField: Int = 42
    }
    println(MY_TABLE.name)
    println(MY_TABLE.myField)
}
You can also make the setters for name and dialect internal if you're making this as a library. Keep in mind that the generics on provideDelegate and getValue is required so that you can access fields of your local object. But yeah this just works and allows you to arbitrarily make any changes to your table
👌 1
r
That's very cool, thanks very much!