I don't think this is possible without an extra pa...
# announcements
s
I don't think this is possible without an extra param in
genericBuilder
, but I don't know all the things.
Copy code
class GenericClass<T> {
    var property: T? = null

    fun genericBuilder(builder: T.() -> Unit) {
        // how to initialize T?
        property?.builder()
    }
}
in js I have this, it 'works' but I don't like it and don't want to use it.
Copy code
interface Person {
    var name: String
    var age: Int
}

interface Car {
    var make: String
    var model: String
}


class ThingHolder<T : Any> {
    var thing: T? = null

    inline fun <reified P : T> thing(builder: P.() -> Unit) {
        val clazz = P::class.js
        thing = js("new clazz()").unsafeCast<P>().apply(builder)
    }
}

fun <T : Any> thingHolderBuilder(builder: ThingHolder<T>.() -> Unit): ThingHolder<T> {
    return ThingHolder<T>().apply(builder)
}

fun main() {
    thingHolderBuilder<Car> {
        thing<Car> {
            make = "Honda"
            model = "Civic"
        }
    }
    thingHolderBuilder<Person> {
        thing<Person> {
            name = "John"
            name = "Doe"
        }
    }
}
r
Creating an unknown generic object is always a hack.
s
Do you have any recommendations on adjusting the builder?
I can add the constructor as a param, but trying to keep the dsl lean
r
Adding a constructor param is often a good way to go, but it depends on your use case.
s
That's what I ended up doing, thanks for the feedback.
👍 1
e
Wrong thread, my b