Kotlin has two types of constructors, primary and secondary. What is the purpose of having two types? In my opinion it makes the code more complicated and inconsistent. If both types of constructors create objects of a class, they are equally important to a class.
Meanwhile, multiple initialisers also introduce confusion and reduce readability.
A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.
In Kotlin, constructor is a block of code similar to method. Constructor is declared with the same name as the class followed by parenthesis '()'. Constructor is used to initialize the variables at the time of object creation.
It is a special member function that is called when an object is instantiated (created). However, how they work in Kotlin is slightly different. In Kotlin, there are two constructors: Primary constructor - concise way to initialize a class. Secondary constructor - allows you to put additional initialization logic.
To do so you need to declare a secondary constructor using the constructor keyword. If you want to use some property inside the secondary constructor, then declare the property inside the class and use it in the secondary constructor.
Primary constructors cover the poplular use case when you need to save the values passed as the constructor arguments to the properties of the instance.
Basically, a primary constructor provides a shorthand for both declaring a property and initializing it from the constructor parameter.
Note that you can do the same without primary constructors at all:
class Foo {
val bar: Bar
constructor(barValue: Bar) {
bar = barValue
}
}
But, since this happens really often in the codebases, Kotlin primary constructors serve the purpose of reducing the boilerplate here:
class Foo(val bar: Bar)
Secondary constructors may complement or replace the primary one in order to support several construction routines for a single class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With