Kotlin中的构造函数与参数



之间有什么区别

class Pitch(var width: Int = 3, var height: Int = 5) {
constructor(capacity: Int): this()
}

class Pitch(var width: Int = 3, var height: Int = 5, capacity: Int)

构造函数提供了哪些优势?

当您这样定义类时:

class Pitch (var width: Int = 3, var height: Int = 5) {
constructor(capacity: Int): this() {}
}

您可以使用不带参数的构造函数创建Pitch的实例,即:

val p = Pitch()
// also you can invoke constructors like this
val p1 = Pitch(30)     // invoked secondary constructor
val p2 = Pitch(30, 20) // invoked primary constructor

当你这样定义你的类时:

class Pitch (var width: Int = 3, var height: Int = 5, capacity: Int) {
}

除具有默认值的参数外,所有参数都是必需的。因此,在这种情况下,您不能使用带有空参数的构造函数,您需要指定至少一个参数capacity:

val p = Pitch(capacity = 40)

因此,在第一种情况下,使用不带参数的构造函数具有优势。在第二种情况下,如果您想调用构造函数并传递capacity参数,那么在使用构造函数时应该显式命名它。

构造函数提供了哪些优势?

在第一个代码段中,您定义了两个构造函数,一个主构造函数和一个辅助构造函数。主构造函数的特殊之处在于,它总是必须由任何辅助构造函数调用。

class Pitch (var width: Int = 3, var height: Int = 5) /* primary constructor */ {
// secondary constructor invokes primary constructor (with default values)
constructor(capacity: Int): this()
}

Pitch()Pitch(10, 20)这两种情况下,都会调用主构造函数。Pitch(10)将调用辅助构造函数。

如果你想调用这个实例化Pitch(10)的主构造函数,你必须像这样明确地指定参数名称:

Pitch(width = 30)

您也可以将其翻转过来,明确设置height,并保留width的默认值:

Pitch(height = 30)

正如您所看到的,使用两个参数(属性),每个参数都有默认值,这给您留下了4种单独通过主构造函数实例化类的可能性。

指定辅助构造函数对于提供实例化类的替代方法特别有用。


像这样使用

class Pitch(var width: Int = 3, var height: Int = 5, capacity: Int)

只有当你不能从widthheight推导出capacity的值时才有意义。所以,这取决于您的用例。

相关内容

最新更新