How to add @JsName to a platform function

I currently have a Multiplatform class called PrettyPrinter with a function called jsonToString. When calling it from Javascript, I need to use the mangled name, although none of my classnames or interfaces are mangled.

new pkg.rjson.PrettyPrinter(opts).jsonToString_vdg2ze$(json)

The generated javascript is

  PrettyPrinter.prototype.jsonToString_vdg2ze$ = function (jsonValue) {
    this.printValue_0(jsonValue);
    return this.buffer_0.toString();
  };

There are no other functions that clash with that name.

I read that using expect and then providing an implementation will allow me to add @JsName, but this is only needed for a single function in a class that has 100 other functions defined, so that seems a bit overkill.

You could do something like this:

// Common module
expect annotation class PlatformName(val name: String)

class PrettyPrinter {
    @PlatformName("jsonToString")
    fun jsonToString...
}

// JS module
actual typealias PlatformName = JsName

// JVM module
// Either create some dummy annotation, or alias to JvmName

This way PlatformName will be transformed to JsName when compiling to JS.

Overall using platform-specific annotations in common code is a bit of a pain. Most likely there will be some simple solution when MPP is released (it is experimental at the moment).

2 Likes

That worked like a charm! Thanks @Anton.Bannykh.

Thank You @Anton.Bannykh its work for me…

and for json to string conversions try this online JSON to String Converter

Thank you @Anton.Bannykh its work for me… also check ounce to cup