use*_*494 0 class-constructors multiple-constructors kotlin
为什么不编译?
class test
{
constructor() {
var a = Date().day
this(a)
}
constructor(a:Int) {
}
}
Run Code Online (Sandbox Code Playgroud)
错误是:无法将类型为“ test”的表达式“ this”作为函数调用。找不到函数“ invoke()”。
建议的解决方案是添加以下内容:
private operator fun invoke(i: Int) {}
Run Code Online (Sandbox Code Playgroud)
为什么?
首先,这两个构造函数都是辅助构造函数。主要构造函数是位于类主体外部的构造函数。
其次,如文档中所述,调用另一个构造函数的正确语法如下:
class Test {
constructor() : this(1) { }
constructor(a: Int) { }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1583 次 |
| 最近记录: |