Can Kotlin do something like this just in valid: `...
# announcements
v
Can Kotlin do something like this just in valid:
inline fun <reified T> options(options: T.() -> Unit): T = object : T {}.apply(options)
?
s
Well there're a couple things wrong here. First, you have no way to guarantee that
T
is open or abstract, or even that it has a no-argument constructor, so creating an anonymous object from it is out. Also, even if you could, generic types aren't constructable that way. I can't give you an effective way to work around this that doesn't take advantage of reflection, but maybe someone else can.
v
T will actually be an interface and everything will have default values. I wanted to make things like this nicer:
Copy code
val result = ncc(input, object : NccOptions {
    override var sourceMap: Boolean? = true
    override var license: String? = "LICENSES"
}).await()
I changed it to
Copy code
val result = ncc(input, object : NccOptions {}.apply {
    sourceMap = true
    license = "LICENSES"
}).await()
Now I thought it could be made like
Copy code
val result = ncc(input, options<NccOptions> {
    sourceMap = true
    license = "LICENSES"
}).await()
with such a method, but it will probably not work even with inline reified types
Ah, scratch that, I'm stupid. That's exactly what
jsObject
is for and even nicer
Copy code
val result = ncc(input, jsObject {
    sourceMap = true
    license = "LICENSES"
}).await()
I somehow thought this would not be typesafe but it is