gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:09:17 25 4
gpt4 key购买 nike

为什么不能编译?

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

constructor(a:Int) {
}
}

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

建议的修复方法是添加:

private operator fun invoke(i: Int) {}

为什么?

最佳答案

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

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

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

constructor(a: Int) { }
}

关于Kotlin 主构造函数调用辅助构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51657535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com