Reputation: 9123
What is the difference between:
class Pitch(var width: Int = 3, var height: Int = 5) {
constructor(capacity: Int): this()
}
and
class Pitch(var width: Int = 3, var height: Int = 5, capacity: Int)
What advantages does the constructor provide?
Upvotes: 2
Views: 585
Reputation: 29844
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.
Upvotes: 1
Reputation: 30625
When you define your class like this:
class Pitch (var width: Int = 3, var height: Int = 5) {
constructor(capacity: Int): this() {}
}
you can create an instance of Pitch
using constructor without parameters, i.e.:
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
When you define your class like this:
class Pitch (var width: Int = 3, var height: Int = 5, capacity: Int) {
}
all parameters are required except those with default values. So in this case you can't use constructor with empty parameters, you need specify at least one parameter capacity
:
val p = Pitch(capacity = 40)
So in the first case you have an advantage of using constructor without parameters. In the second case if you want to call constructor and pass capacity
parameter you should name it explicitly when using constructor.
Upvotes: 2