Kotlin Constructor

In this tutorial you will learn about the Kotlin Constructor and its application with practical example.

Kotlin Constructor

A class in Kotlin can have a primary constructor(The header of class) and one or more secondary constructors. The primary constructor goes after the class name. The constructor is way to initialize class properties.

Table Of Contents

Kotlin Primary Constructor

Syntax :-

Here, block of code which is surrounded by parentheses is represents a primary constructor. It have two properties tutorial and rating (val article: String, var review: Int)

Example: Let’s get understand it by an example.

Output :- sdf

constructor-1

Primary Constructor with Initializer Blocks

The primary constructor can not contain code, it has constrained syntax. For initialization code we used initializer block with init keyword. Check below example for know more.

Output :- sdfsd

constructor-2

Kotlin Secondary Constructor

A class can contain one or more secondary constructor in Kotlin using constructor keyword. It is required when you required more than one constructor in Kotlin class.
When you need to extend a class which provides multiple constructors that initialize the class in different ways , the Secondary Constructor is used for this.

Creation of Secondary Constructor: Let’s see how you can create a secondary constructor in Kotlin.

Here, you can see in above code that SecondaryConstructorDemo1 is not has primary constructor.

 

Example: Let’s understand it by an example.

Output: The below image will be output of this code.

constructor-3

In this tutorial we have learn about the Kotlin Constructor and its application with practical example. I hope you will like this tutorial.