如何在Kotlin中创建JavaScript匿名对象?我想创建这个对象并将其传递给Node.js应用程序。
var header = {“content-type”:”text/plain” , “content-length” : 50 ...}
可能的解决方案:
1)使用js
函数:
val header = js("({'content-type':'text/plain' , 'content-length' : 50 ...})")
注:括号必须使用dynamic
:val d: dynamic = object{}
d["content-type"] = "text/plain"
d["content-length"] = 50
3)使用 js
和 dynamic
:
val d = js("({})")
d["content-type"] = "text/plain"
d["content-length"] = 50
4) 使用本地声明:
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
}
这是一个帮助函数,使用lambda语法初始化对象
inline fun jsObject(init: dynamic.() -> Unit): dynamic {
val o = js("{}")
init(o)
return o
}
使用方法:
jsObject {
foo = "bar"
baz = 1
}
生成的 JavaScript 代码
var o = {};
o.foo = 'bar';
o.baz = 1;
还有一种可能的解决方案:
object {
val `content-type` = "text/plain"
val `content-length` = 50
}
看起来使用转义变量名称不再起作用了。
kotlin.js.json
的解决方案。val options = json(
"position" to "top-right",
"durations" to json(
"global" to 20000
)
)
我是 Kotlin 的新手(虽然不是新手开发者),我稍微扩展了 @bashor 的答案,使其对于有效的 Java 标识符键更加整洁,但仍允许那些无效的键。我已经在 Kotlin 1.0.1 中进行了测试。
@JsName("Object")
open class Object {
}
fun jsobject(init: dynamic.() -> Unit): dynamic {
return Object().apply(init)
}
header = jsobject {
validJavaIdentifier = 0.2
this["content-type"] = "text/plain"
this["content-length"] = 50
}
Object()
may be replaced with js("{}")
- Vladfun jsObject(init: dynamic.() -> Unit) = js("{}").apply(init)
。 - Vladfun jsObject(vararg pairs: Pair<Any, Any>): dynamic {
val result = js("({})")
for ((key, value) in pairs) {
result[key] = value
}
return result
}
然后您可以按照以下方式使用它
val header = jsObject("content-type" to "text/plain", "content-length" to 50)
使用JavaScript的Object.assign()
,可以将普通的Kotlin对象转换为JavaScript匿名对象。这样可以让您尽可能地保持在纯Kotlin和类型安全中。因此:
fun Any.toJsObject(): dynamic {
val thisArg = this // Allows use in js() function
return js("Object.assign({},thisArg)")
}
val anObject = object { val a = "a" } // Or use a regular class
console.log( anObject.toJsObject().a ) // logs "a"