Importation of JS functions in Kotlin

Dear all,

Is there any possibility to import some JS file (example.js) with function e.g:

function myFunction(p1, p2) {
return p1 * p2;
}

into Kotlin main function and using it like

fun main() {
myFunction(5,5)
}

or to import any other JS files and using their functions in the main function in the .kt file?

Thanks a lot

https://kotlinlang.org/docs/js-interop.html

I found this, but it is not working if I try to change things dynamically. E.G. calling js(“something”), this “something” must be a non-changeable string. I need to use interpolation and this is not acceptable in js().

Any suggestion on how to do this?

Look at the external modifier. It is described in much detail in that documentation.

Yes, but still I can not do pretty much. (BTW, I am new in JS and Kotlin).

Can you, please, share some examples, ideas, something?

The first thing to learn about is JavaScript modules. You need to put your Javascript function into a Javascript module. However there are many different module standards in JavaScript. The first thing you should do is learning how to use them.

Search for tutorials describing JavaScript modules. Learn how to use them. Write your own small JavaScript project that imports JavaScript modules.

Once you have learned about JavaScript modules, you can search for Kotlin tutorials that describe how to use and import JavaScript modules into Kotlin code.

Hi alzomins,
did you then find a solution? I have the same problem, I don’t know how to invoke from my kotlin main activity a function that I have defined inside a .js file. I am a newbie to android studio. I don’t know how to import the .js file into the kotlin project I don’t know how to make my function visible from the kotlin code.
If you have already found a solution and can share it I would be very grateful.
Thanks, see you soon

1 Like