Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Kotlin have two types of constructors?

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.

like image 584
Jia Li Avatar asked Jul 26 '18 14:07

Jia Li


People also ask

What are the two types of constructors in Kotlin?

A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.

What is the use of constructor in Kotlin?

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.

What are constructors explain their types Kotlin?

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.

How does Kotlin define secondary constructor?

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.


1 Answers

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.

like image 156
hotkey Avatar answered Oct 19 '22 16:10

hotkey