2

有什么区别:

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)

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

4

2 回答 2

2

当你像这样定义你的类时:

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参数,则应在使用构造函数时显式命名。

于 2019-01-26T07:38:35.057 回答
1

What advantages does the constructor provide?

In your first snippet you define two constructors, one primary and one secondary. This special thing about the primary constructor is that is always has to be invoked by any secondary constructor.

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

In both cases: Pitch() and Pitch(10, 20) the primary constructor is invoked. Pitch(10) would invoke the secondary constructor.

If you want to invoke the primary constructor for this instantiation Pitch(10) you have to specify the parameter name explicitely like this:

Pitch(width = 30)

You can also turn it around and set height explicitely and leave width with its default value:

Pitch(height = 30)

As you see using two parameters (properties) with default values for each leaves you with 4 possibilities to instantiate the class via primary constructor alone.

Specifying a secondary constructor is especially useful to provide an alternative way to instantiate a class.


Using it like this

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

would only make sense when you can't deduce the value of capacity from width and height. So, it depends on your use-case.

于 2019-01-26T14:21:28.187 回答