javascript anonymous object in kotlin
In my Kotlin/JS + React project I have written an adapter for a library that accepts an anonymous configuration object through the constructor. After searching for a while I found a solution using kotlin.js.json
val options = json(
"position" to "top-right",
"durations" to json(
"global" to 20000
)
)
Here's a helper function to initialize an object with a lambda syntax
inline fun jsObject(init: dynamic.() -> Unit): dynamic {
val o = js("{}")
init(o)
return o
}
Usage:
jsObject {
foo = "bar"
baz = 1
}
Emited javascript code
var o = {};
o.foo = 'bar';
o.baz = 1;
Possible solutions:
1) with js
function:
val header = js("({'content-type':'text/plain' , 'content-length' : 50 ...})")
note: the parentheses are mandatory
2) with dynamic
:
val d: dynamic = object{}
d["content-type"] = "text/plain"
d["content-length"] = 50
3) with js
+ dynamic
:
val d = js("({})")
d["content-type"] = "text/plain"
d["content-length"] = 50
4) with native declaration:
native
class Object {
nativeGetter
fun get(prop: String): dynamic = noImpl
nativeSetter
fun set(prop: String, value: dynamic) {}
}
fun main(args : Array<String>) {
var o = Object()
o["content-type"] = "text/plain"
o["content-length"] = 50
}
One more possible solution:
object {
val `content-type` = "text/plain"
val `content-length` = 50
}
It seems that it does not work anymore with escaped variable names.