Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin主构造函数调用辅助构造函数_Kotlin_Class Constructors_Multiple Constructors - Fatal编程技术网

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

Kotlin主构造函数调用辅助构造函数,kotlin,class-constructors,multiple-constructors,Kotlin,Class Constructors,Multiple Constructors,为什么不编译 class test { constructor() { var a = Date().day this(a) } constructor(a:Int) { } } 错误是: 类型为“test”的表达式“this”不能作为函数调用。找不到函数“invoke()” 建议的修复方法是添加以下内容: private operator fun invoke(i: Int) {} 为什么?首先,这两个构造函数都是次要构造函数。主构造函数是位于类主

为什么不编译

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) { }
}

这里有两个问题:

  • 类的名称应始终使用驼峰大小写(
    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
    }
}
如果类定义了
主构造函数
次构造函数
需要委托给
主构造函数
。看

我认为
主构造函数
不能从
次构造函数
调用

您可以这样想:辅助调用primary和primary调用secondary=>无尽循环=>不可能

在您的例子中,有2个
二级构造函数
,因此您可以像

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{constructor(){var a=Date()。day this(a)}构造函数(a:Int){},您不能这样做。这是一个JVM限制。如果这是可能的,则在执行
var a=Date()
期间,对象将以未初始化状态存在,这是不允许的。请稍候。。。根据您计算的内容,您可以,例如,您可以写:
constructor():this(Date().day)
,或者我只是没有正确理解您的问题;-)如果这是一个更复杂的计算,但您从某个新实例开始,您可以使用类似于
constructor():this(ComplexObject()。让{/*导致Int*/}的复杂函数
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) {
    }
}