Kotlin for JavaScript的可配置工厂

我有一个Kolin类A,它的属性是在主构造器中提供的,或者是由A的次构造器中的工厂创建的。

interface I class O : I class A (val i: I) { constructor(): this(factory!!.create()) } interface Factory { fun create(): I } class MyFactory: Factory { override fun create(): I { return O() } } var factory: Factory? = null fun main(args: Array<String>) { factory = MyFactory() A() } 

当我将这些代码编译成JavaScript(Kolin编译器版本1.0.6-release-127)并在浏览器(Safari 10.0.3)中运行它时,出现以下运行时错误:

 ReferenceError:Can't find variable: tmp$0 

该错误发生在A的二级构造函数中。似乎Kolin在二级构造函数中执行参数的空检查时出现问题。 当我将工厂声明更改为“not null”并从main()方法中删除工厂初始化时,代码正确运行:

 val factory: Factory = MyFactory() fun main(args: Array<String>) { A() } 

但这不是我想要的,因为我希望能够在应用程序启动时配置工厂。

我错过了什么,或者这是Kotlin的JavaScript编译器中的错误? 有没有人知道这个问题的解决方法? 是否有另一种或更好的方法来设计Kotlin for JavaScript中的可配置工厂?

生成的JavaScript代码:

 var KotlinTest = function (Kotlin) { 'use strict'; var _ = Kotlin.defineRootPackage(function () { this.factory = null; }, /** @lends _ */ { I: Kotlin.createTrait(null), O: Kotlin.createClass(function () { return [_.I]; }, function O() { }), A: Kotlin.createClass(null, function A(i) { this.i = i; }), A_init: function ($this) { $this = $this || Object.create(_.A.prototype); _.A.call($this, ((tmp$0 = _.factory) != null ? tmp$0 : Kotlin.throwNPE()).create()); return $this; }, Factory: Kotlin.createTrait(null), MyFactory: Kotlin.createClass(function () { return [_.Factory]; }, function MyFactory() { }, /** @lends _.MyFactory.prototype */ { create: function () { return new _.O(); } }), main_kand9s$: function (args) { _.factory = new _.MyFactory(); _.A_init(); } }); Kotlin.defineModule('KotlinTest', _); _.main_kand9s$([]); return _; }(kotlin); 

回答我自己的问题。 正如@marstran正确地评论说的,这似乎是一个在Kolin的Javascript编译器1.0.6中的错误,它似乎在1.1-beta版本中得到了修复。 与此同时,我正在使用类似于以下的解决方法:

 interface I class O : I class A (val i: I) { constructor(): this(Factory.get().create()) } interface Factory { companion object { private var IMPL : Factory? = null fun get(): Factory = IMPL!! fun set(impl: Factory) { IMPL = impl } } fun create(): I } class MyFactory: Factory { override fun create(): I { return O() } } fun main(args: Array<String>) { Factory.set(MyFactory()) A() }