how to create JavaScript anonymous object in kotlin? i want to create exactly this object to be passed to nodejs app
var header = {“content-type”:”text/plain” , “content-length” : 50 ...}
Creating Anonymous Objects From an Interface In Kotlin, as interfaces cannot have constructors, the object expression's syntax changes to: object : TheInterface { ... implementations ... } As the code above shows, our anonymous class has overridden the content property and implemented the print function.
Anonymous object in Java means creating an object without any reference variable. Generally, when creating an object in Java, you need to assign a name to the object. But the anonymous object in Java allows you to create an object without any name assigned to that object.
To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.
Kotlin uses object expression to achieve the same functionality. We can even create an object expression for an interface or abstract class by just implementing their abstract methods. This functionality is called an anonymous interface implementation or anonymous abstract class implementation.
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
}
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With