Kotlin JS doesn't add “new” keyword where needed

I am creating interactive infographics using Google Charts and Kotlin JS. This is snippet from Quick Start Page.

var data = new google.visualization.DataTable();
<..>
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

Here “new” keyword is used. I tried to rewrite this code using Kotlin.

val data = google.visualization.DataTable();
<..>
val chart = google.visualization.PieChart(document.getElementById('chart_div'));

But an error occurred saying that “new” keyword is missing in lines above. So Kotlin to JS compiler haven’t added the keyword where they should be.

Is there correct way to avoid the error without using js() function?

Thank you.

Maybe something wrong with your external declarations? With this one Kotlin generates correct code:

external object google {
	object visualization {
		class DataTable
	}
}
1 Like

I am solving similar problem, need to create instance of js showdown.Converter.

I have declared external dependence as you suggested

external object showdown {
    class Converter(options: Any?) {
        fun makeHtml(text: String): String;
    }
}

but

val a = showdown.Converter(null);

is compiled to

var a = new showdown$Converter(null);

Any idea how to declare it to be compiled to propper JS form with dot? Thanx :wink:

I played a bit with the kotlin playgound, and I found that kotlin indeed produces new showdown$Converter(null);, but it also allocates a variable named that way and assign it the correct constructor : var showdown$Converter = showdown.Converter;.

I don’t really know why it does this trick, but in the end the call to the constructor should work.

2 Likes

My guess is that is has to do with object/nested object naming on the JVM. It’s probably easier for the kotlin compiler to use the same internal object names everywhere and just add the extra variable instead of using 2 different ways to refer to the nested object.

3 Likes