kotlinkotlin-js

javascript anonymous object in kotlin


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 ...}

Solution

  • 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
    }