【发布时间】:2017-02-14 03:48:15
【问题描述】:
我有一个 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在二级构造函数中对某个参数进行null检查有问题。当我将工厂声明更改为“not null”并从 main() 方法中删除工厂初始化时,代码运行正常:
val factory: Factory = MyFactory()
fun main(args: Array<String>) {
A()
}
但这不是我想要的,因为我希望能够在应用程序启动时配置工厂。
我是否遗漏了什么,或者这是 Kotlin 的 JavaScript 编译器中的错误?有人知道这个问题的解决方法吗?是否有其他或更好的方法可以在 Kotlin 中为 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);
【问题讨论】:
-
这似乎是 Kotlin 1.0.6 版本的 Javascript 编译器中的一个错误。我在 1.0.6 和 1.1-beta 版本中都尝试了您的示例,并且它适用于后一个版本。
标签: kotlin