首页 > 解决方案 > Kotlin 主构造函数调用辅助构造函数

问题描述

为什么这不编译?

class test
{
  constructor() {
      var a = Date().day
      this(a)
  }

  constructor(a:Int) {
  }
}

错误是:“test”类型的表达式“this”不能作为函数调用。未找到函数“invoke()”。

建议的解决方法是添加以下内容:

private operator fun invoke(i: Int) {}

为什么?

标签: kotlinclass-constructorsmultiple-constructors

解决方案


首先,这两个构造函数都是辅助构造函数。主构造函数是位于类主体之外的构造函数。

其次,如文档中所述,调用另一个构造函数的正确语法如下:

class Test {
    constructor() : this(1) { }

    constructor(a: Int) { }
}

推荐阅读