1

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. Here is compiled JavaScript code.

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

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

Thank you.

6
  • Could you also share the javascript code compiled from these kotlin lines? Commented Nov 10, 2019 at 3:55
  • @Ilya Ok, done it. Commented Nov 10, 2019 at 14:28
  • If I'm reading this thread correctly, it looks like you need to use the js function for all native Javascript object creation anyway. Is your avoidance of js on principle, or did you see this type of call work without the js function elsewhere? Commented Nov 10, 2019 at 14:54
  • 1
    I would guess it's because a JavaScript function can be called with and without new, meaning very different things, and KT doesn't know which you mean. Commented Nov 10, 2019 at 15:14
  • 2
    @ЕгорПономарёв Yes, but that's a Kotlin class, not an arbitrary expression (google.visualization.DataTable); as far as Kotlin knows, maybe DataTable is a plain function. Perhaps you need corresponding external class headers as XMLHttpRequest does, but even then it's unclear whether it would work with the built-in google.visualization namespacing. Commented Nov 10, 2019 at 15:15

1 Answer 1

2

The reason why the new keyword was not added is because google variable hadn't been added with external keyword. With this one Kotlin generates correct code.

external object google {
    object visualization {
        class DataTable
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.