Integrating Kotlin code into a Typescript (e.g. Angular) Application

I love kotlin, I love the multi platform feature of Koltin.
As such I have now built a few (different sized) applications with a Kotlin backend, and an Angular frontend, using Koltin common classes as a means to communicate data between back and front.

Of course, there were issues, some of which I have over come. Some still to be satisfactorily solved.

An account of the issues and solutions can be found here
building-applications-with-kotlin-and-typescript

However, there are still two open issues, detailed at the end of the article. I would appreciate any help or suggestions on how to solve these issues or improve any other aspect.

Open issues:

  • calling methods on Koltin (stdlib) types from Javascript/Typescript (name mangling is a problem)
  • discovering the module name of the kotlin generated JS module.
1 Like

There is an annotation for that. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-js-name/index.html
This allows you to specify the Js name of a given function/property thereby negating the need for name mangling.
There have been discussions about a way to specify that no mangling should be done at all, but I don’t think there is any progress on that front. The problem is that name mangling is necessary due to function overloads, but I think you mentioned that already in your article.
My hope is that this will be resolved in the future, maybe a system for js which does not mangle names but instead fails if an overload does not have a JsName annotation.

I’m not sure about the second problem. Maybe this can be solved with the new klib format for multiplatform libraries, which will be an experimental part of kotlin 1.4.

sorry, I forgot to explicitly state ‘stdlib’ types.
I know about the JSNam annotation, it doesn’t help if the original author of the type has not added it.

If you’re referring to data structures like lists and maps from the stdlib, I don’t think you can or should use them directly in typescript due to the way they’re structured. Your best bet is probably to convert them to JS arrays via the .toArray() function or for a map use json(map.entries.map { it.toPair() }) before using them in the typescript world.

Otherwise, you can just make wrappers for stdlib functions and expose them to TypeScript via the @JSName annotation as described earlier. Kotlin/JS isn’t as interoperable with JS/TS as Kotlin/JVM is with Java, unfortunately.

For Sets and Lists, yes we can use toArray(), but for Map, it would be a whole lot easier if we could use the get/set/put methods. and even for Set and List, it would be nicer to use ‘add’ etc.

Is there any reason that the stdlib cannot make use of the @JSName annotation for methods such as these? (there are probably many other examples where it would be useful)

From what I recall, method mangling occurs by default because JavaScript does not support method overloading.