javascript anonymous object in kotlin

前端 未结 6 1908
终归单人心
终归单人心 2021-02-07 09:18

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” ,          


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 09:50

    It is possible to transform a regular Kotlin object into a JavaScript anonymous object using JavaScript's Object.assign(). This allows you to stay in pure Kotlin and in type-safety as long as possible. So:

    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"
    

提交回复
热议问题