Kotlin主构造函数正在调用辅助构造函数



为什么不编译?

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

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

建议的修复方法是添加以下内容:

private operator fun invoke(i: Int) {}

为什么?

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

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

class Test {
constructor() : this(1) { }
constructor(a: Int) { }
}
class test constructor(){ // primary constructor (The primary constructor is part of the class header: it goes after the class name (and optional type parameters))
constructor(a: Int) : this() { // secondary constructor
}
}

如果类已经定义了primary constructor,则secondary constructor需要委托给primary constructor。请参见此处。

我认为primary constructor不能从secondary constructor调用

你可以这样想:次要呼叫主要和主要呼叫次要=>无休止循环=>不可能

在你的情况下,有2个secondary constructor,所以你可以像一样

class test {
constructor() : this(Date().day) // I see it quite like Java here https://stackoverflow.com/questions/1168345/why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor
constructor(a: Int) {
}
}

这里有几个错误:

  • 类的名称应始终使用驼色大小写(test->Test(
  • 无法在尝试时调用另一个构造函数(在其他构造函数体内部调用this(1)(

我认为您实际想要的是a作为一个属性,并使用默认值对其进行初始化。你可以这样做

class Test(val a: Int) {
constructor() : this(1) // notice how you can omit an empty body
}

甚至更好,像这样:

class Test(val a: Int = 1) // again an empty body can be omitted.

编辑:

如果你需要做一些计算,正如Yole回答下面的评论所问:

class Test(val day: Int) {
// you can use any expression for initialization
constructor(millis: Long) : this(Date(millis).day) 
}

或者如果事情变得更复杂:

class Test(var day: Int) {
// pass something (i.e. 1) to the primary constructor and set it properly in the body
constructor(millis: Long) : this(1) { 
// some code
day = // initialize day
}
}

最新更新