Primary & Secondary Constructors & init Block in Kotlin

The class declaration consists of the class name, the class header (specifying its type parameters, the primary constructor etc.) and the class body, surrounded by curly braces. Both the header and the body are optional; if the class has no body, curly braces can be omitted.

Before starting, let’s think of a situation where you and your friend are walking on a road and somebody calls you by your name. What will you do? You will immediately turn back and respond. This is called Constructor. Here you are the class, with your name as the class name. Whenever someone calls you, with your name, you respond immediately. So, a Constructor is something that is called just after the creation of object i.e. whenever you are called by your name you will respond and this responding is the work that the constructor does.

A constructor is a concise way to initialize class properties.

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

So, in this blog, we will learn about constructors in Kotlin. We will cover Primary Constructors, init() block and Secondary Constructors. So, let’s get started.

What are Constructors?
Before moving on to constructors, let’s take an example, suppose there is a class named Person, then the properties of the class will be the name of the person, age of the person, the salary of the person, etc.

The main purpose of constructor is to initialize the properties of a class. Constructor is called when we create the object of a class. In Kotlin we have two types of constructor – primary and secondary constructor. In this guide, we will learn primary and secondary constructor with example, we will also learn about initializer blocks.

So, properties are those things which help to identify you. For example, a person is identified by his name, age or place of living. There can be more than one property of a class and all of these properties must be initialized when an object is created and in order to initialize the properties of an object, we use Constructors.

Leave a Reply

Your email address will not be published. Required fields are marked *