kotlin - 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) { }
}
推荐阅读
- php - 我正在努力获取 api 任何功能
- r - Error_bar 和练习
- algorithm - 允许图的并发游走的算法
- c# - 如何在没有管理员访问权限的情况下以编程方式卸载 UWP 应用程序 c#
- c# - 如何将 C# 类映射到角度对象
- php - 通过 $_ENV 使用 .env 文件中的参数是否正常?
- rust - 无法释放文件。出现错误:无法编译“libc”
- android - 如何在 Android Studio Java 中将 Json 字符串转换为 Json 数组
- docker - 无法回显 docker 容器中的 env var
- selenium-webdriver - 在线程组和采样器之间传递变量