C.A.B.
C.A.B.

Reputation: 583

How to call Javascript function from Kotlin code?

I am trying to compile Kotlin code as Javascript. In my code I need to encode string as URI. My 2 variants are both fail compilation:

class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
    return encodeURIComponent(str)
}

In this code compiler cannot find function encodeURIComponent(str), which according to https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp is supported by all browsers.

Alternative:

class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
    return URLEncoder.encode(str, Charsets.UTF_8.name())
} 

cannot find Java class URLEncoder (imported in the file as in Java). This works when compiled for JVM, but not JS.

Also I have Kotlin module marked with:

compileKotlin2Js.kotlinOptions.moduleKind = "umd"

Upvotes: 2

Views: 1386

Answers (1)

C.A.B.
C.A.B.

Reputation: 583

I found that latest way to declare Javascript function in Kotlin is:

external fun encodeURIComponent(str: String): String

Once added it to the Kotlin class everything get compiled without a problem.

Upvotes: 4

Related Questions