Calling Kotlin from JavaScript

Calling Kotlin from JavaScript

Kotlin compiler generates normal JavaScript classes, functions and properties you can freely use from JavaScript code. Nevertheless, there are some subtle things you should remember.

Isolating declarations in a separate JavaScript object

To prevent spoiling the global object, Kotlin creates an object that contains all Kotlin declarations from the current module. So if you name your module as myModule, all declarations are available to JavaScript via myModule object. For example:

fun foo() = "Hello"

Can be called from JavaScript like this:

alert(myModule.foo());

This is not applicable when you compile your Kotlin module to JavaScript module (see JavaScript Modules