Freewind
Freewind

Reputation: 198198

How to use Kotlin to generate a javascript function `constructor`?

I want to use Kotlin to generate some JavaScript like following:

function MyComponent() {
    self.constructor = function() {}
}

The problem is constructor is a keyword in Kotlin, I can't just write like:

class MyComponent {
  fun constructor() {}
}

I also tried:

class MyComponent {
    @JsName("constructor")
    fun ctor() {}
}

It still report errors like:

JavaScript name generated for this declaration clashes 
with built-in declaration {1}

How to generate a javascript function which has name constructor?

Upvotes: 2

Views: 339

Answers (1)

Anton Bannykh
Anton Bannykh

Reputation: 144

There should be no problem with the top-level functions. The fun constructor() {} should just work, yielding function constructor(){}. At least that's what it does in Kotlin 1.2.31.

On the other hand member functions named constructor are prohibited (e.g. you cannot get A.prototype.constructor = function () {} in the output js file). For one thing that would ruin the is-check implementation.

Modifying the constructor property inside the class constructor should be possible:

// Kotlin
class A {
  init{
    this.asDynamic().constructor = fun(a: Int) { println(a) }
  }
}

// JS
function A() {
  this.constructor = A_init$lambda;
}
function A_init$lambda(a) {
  println(a);
}

Hope that helped.

Upvotes: 2

Related Questions