Search code examples
kotlinkotlin-jskotlin-js-interop

Is it possible to call kotlin's js function with an interpolated string template?


Right now, IntellJ is showing a red squiggly line saying: Argument must be a string constant

private fun fromEnv(name: String) {
    return js("process.env[${name}]") as Unit
}

I've searched but I have not found any similar question.


Solved by @alexey-romanov

It's just as simple as:

private fun fromEnv(name: String) {
    return js("process.env[${name}]") as Unit
}

which compiles to:

function fromEnv(name) {
  var tmp$;
  return typeof (tmp$ = process.env[name]) === 'string' ? tmp$ : throwCCE();
}

Solution

  • No, it isn't. But you can just use name in the code argument to js:

    private fun fromEnv(name: String) {
         js("process.env[name]")
    }
    

    This example is pretty much the same as the use of the variable o in the Inline Javascript section of documentation:

    fun jsTypeOf(o: Any): String {
        return js("typeof o")
    }