Open In App

Kotlin Constructor

Last Updated : 30 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A constructor is a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. A class needs to have a constructor and if we do not declare a constructor, then the compiler generates a default constructor. Kotlin has two types of constructors:

  1. Primary Constructor
  2. Secondary Constructor 

A class in Kotlin can have at most one primary constructor, and one or more secondary constructors. The primary constructor initializes the class, while the secondary constructor is used to initialize the class and introduce some extra logic.

Primary Constructor

The primary constructor is initialized in the class header, and goes after the class name, using the constructor keyword. The parameters are optional in the primary constructor.

class Add constructor(val a: Int, val b: Int) {
// code
}

The constructor keyword can be omitted if there is no annotations or access modifiers specified.  

class Add(val a: Int, val b: Int) {
// code
}

Kotlin program of primary constructor:

Kotlin




// main function
fun main(args: Array<String>)
{
    val add = Add(5, 6)
    println("The Sum of numbers 5 and 6 is: ${add.c}")
}
 
// primary constructor
class Add constructor(a: Int,b:Int)
{
    var c = a+b;
}


Output: 

The Sum of two numbers is: 11

Explanation:

When we create the object add for the class then the values 5 and 6 passes to the constructor. The constructor parameters a and b initialize with the parameters 5 and 6 respectively. The local variable c contains the sum of variables. In the main, we access the property of constructor using ${add.c}.

Primary Constructor with Initializer Block

The primary constructor cannot contain any code, the initialization code can be placed in a separate initializer block prefixed with the init keyword.

Kotlin program of primary constructor with initializer block 

What is init block? 

It acts as an initialiser block where member variables are initialised. This block gets executed whenever an instance of this class is created. There can be multiple init blocks and they are called in the order they are written inside the class.

Note: init blocks gets called before the constructor of this class is called.

Kotlin




class Person (val _name: String) {
    
   // Member Variables
   var name: String
 
   // Initializer Blocks
   init{
        println("This is first init block")
    }
     
    init{
        println("This is second init block")
    }
     
    init{
        println("This is third init block")
    }
    init {
      this.name = _name
      println("Name = $name")
   }
}
 
fun main(args: Array<String>) {
   val person = Person("Geeks")
}


Output: 

This is first init block
This is second init block
This is third init block
Name = Geeks

Explanation:

When the object person is created for the class Person, the value “Mahmood” is passed to the parameters name of the constructor. Two properties are declared in the class id and name.

Initializer block is executed at the time of object creation, and not only initializes the properties but also prints to the standard output.

Default value in primary constructor

Similar to function default values in functions, we can initialize the constructor parameters with some default values.

Kotlin program of default values in primary constructor:

Kotlin




fun main(args: Array<String>) {
    val emp = employee(18018, "Sagnik")
    // default value for emp_name will be used here
    val emp2 = employee(11011)
    // default values for both parameters
      // because no arguments passed
    val emp3 = employee()
}
 
class employee(emp_id : Int = 100 , emp_name: String = "abc") {
    val id: Int
    var name: String
 
    // initializer block
    init {
        id = emp_id
        name = emp_name
 
        print("Employee id is: $id, ")
        println("Employee name: $name")
        println()
    }
}


Output: 

Employee id is: 18018, Employee name: Sagnik
Employee id is: 11011, Employee name: abc
Employee id is: 100, Employee name: abc

Explanation:

Here, we have initialized the constructor parameters with some default values emp_id = 100 and emp_name = “abc”. When the object emp is created we passed the values for both the parameters, so it prints those values. 
But, at the time of object emp2 creation, we have not passed the emp_name so initializer block uses the default values and print to the standard output. 

Secondary Constructor

As mentioned above, Kotlin may have one or more secondary constructors. Secondary constructors allow initialization of variables and allow to provide some logic to the class as well. They are prefixed with the constructor keyword.

Kotlin program of implementing secondary constructor:

Kotlin




// main function
fun main(args: Array<String>)
{
    Add(5, 6)
}
 
// class with one secondary constructor
class Add
{
    constructor(a: Int, b:Int)
    {
        var c = a + b
        println("The sum of numbers 5 and 6 is: ${c}")
    }
}


Output: 

The sum of numbers 5 and 6 is: 11

Which secondary constructor will be called is decided by the compiler based on the arguments received. In the above program, we do not specify to invoke which constructor and compiler decides by itself.

Kotlin program of two secondary constructors in a class:  

Kotlin




fun main(args: Array<String>) {
    employee(18018, "Sagnik")
    employee(11011,"Praveen",600000.5)
}
class employee {
      constructor (emp_id : Int, emp_name: String ) {
          var id: Int = emp_id
          var name: String = emp_name
          print("Employee id is: $id, ")
          println("Employee name: $name")
          println()
      }
 
       constructor (emp_id : Int, emp_name: String ,emp_salary : Double) {
           var id: Int = emp_id
           var name: String = emp_name
           var salary : Double = emp_salary
           print("Employee id is: $id, ")
           print("Employee name: $name, ")
           println("Employee name: $salary")
       }
}


Output: 

Employee id is: 18018, Employee name: Sagnik
Employee id is: 11011, Employee name: Praveen, Employee name: 600000.5

Kotlin program of three secondary constructors in a class:

Kotlin




// main function
fun main(args: Array<String>)
{
    Add(5, 6)
    Add(5, 6, 7)
    Add(5, 6, 7, 8)
}
 
// class with three secondary constructors
class Add
{
    constructor(a: Int, b: Int)
    {
        var c = a + b
        println("Sum of 5, 6 = ${c}")
    }
    constructor(a: Int, b: Int, c: Int)
    {
        var d = a + b + c
        println("Sum of 5, 6, 7 = ${d}")
    }
    constructor(a: Int, b: Int, c: Int, d: Int)
    {
        var e = a + b + c + d
        println("Sum of 5, 6, 7, 8 = ${e}")
    }
}


Output: 

Sum of 5, 6 = 11
Sum of 5, 6, 7 = 18
Sum of 5, 6, 7, 8 = 26

Calling one secondary constructor from another

A secondary constructor may call another secondary constructor of the same class using this() function. In the below program, we have called another constructor using this(a,b,7) because invoking of that constructor requires three parameters.

Kotlin program of calling one constructor from another:

Kotlin




// main function
fun main(args: Array<String>)
{
    Add(5,6)
}
class Add {
    // calling another secondary using this
    constructor(a: Int,b:Int) : this(a,b,7) {
        var sumOfTwo = a + b
        println("The sum of two numbers 5 and 6 is: $sumOfTwo")
    }
     
    // this executes first
    constructor(a: Int, b: Int,c: Int) {
        var sumOfThree = a + b + c
        println("The sum of three numbers 5,6 and 7 is: $sumOfThree")
    }
}


Output:

The sum of three numbers 5,6 and 7 is: 18
The sum of two numbers 5 and 6 is: 11

Calling parent class secondary constructor from child class secondary constructor

We can call the secondary constructor of parent class from the child class using the super keyword. In the below program, we have shown the process of calling. 

As you can see here is a new keyword called open, an open class is an ordinary class that is open for extension. By default, when you write a class in Kotlin, it cannot be extended. Yes, inheritance is prevented by default. By declaring a class to be open, you tell the compiler: “I intend to extend this class”.

Kotlin




fun main(args: Array<String>) {
    Child(18018, "Sagnik")
}
 
open class Parent {
    constructor (emp_id: Int, emp_name: String, emp_salary: Double) {
        var id: Int = emp_id
        var name: String = emp_name
        var salary : Double = emp_salary
        println("Employee id is: $id")
        println("Employee name: $name")
        println("Employee salary: $salary")
        println()
    }
}
class Child : Parent {
    constructor (emp_id : Int, emp_name: String):super(emp_id,emp_name,500000.55){
        var id: Int = emp_id
        var name: String = emp_name
        println("Employee id is: $id")
        println("Employee name: $name")
    }
}


Output: 

Employee id is: 18018
Employee name: Sagnik
Employee salary: 500000.55
Employee id is: 18018
Employee name: Sagnik


Previous Article
Next Article

Similar Reads

How to Initialize Constructor in Kotlin?
Constructor is a concise way to initialize class properties. or we can say it's a special member function that is invoked when an object of the class is created primarily to initialize variables or properties. A class needs to have a constructor and if we do not declare a constructor, then the compiler generates a default constructor. It is a speci
4 min read
Kotlin Data Types
The most fundamental data type in Kotlin is the Primitive data type and all others are reference types like array and string. Java needs to use wrappers (java.lang.Integer) for primitive data types to behave like objects but Kotlin already has all data types as objects. There are different data types in Kotlin: Integer Data typeFloating-point Data
3 min read
Hello World program in Kotlin
Hello, World! is the first basic program in any programming language. Let's write the first program in Kotlin programming language. The "Hello, World!" program in Kotlin: Open your favorite editor notepad or notepad++ and create a file named firstapp.kt with the following code. // Kotlin Hello World Program fun main(args: Array&lt;String&gt;) { pri
2 min read
Android Shared Element Transition with Kotlin
Shared element transition is seen in most of the applications which are used when the user navigates between two screens. This type of animation is seen when a user clicks on the items present in the list and navigates to a different screen. During these transitions, the animation which is displayed is called a shared element transition. In this ar
4 min read
Kotlin | Retrieve Collection Parts
The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying the start and end indices of the sublist. The result
5 min read
Destructuring Declarations in Kotlin
Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once. For example : val (emp_id,salary) = employee These multiple variables correspond to the properties of a class that are associat
3 min read
Why Kotlin will replace Java for Android App Development
We have a new member in our programming languages family and it’s none other than Kotlin. In Google I/O ‘17, they have finally announced that for android the official first class support will be given to the Kotlin. We can almost say that Kotlin is officially in for android development and java is almost getting pushed out of the frame. While java
4 min read
DatePicker in Kotlin
Android DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePic
3 min read
Kotlin labelled continue
In this article, we will learn how to use continue in Kotlin. While working with a loop in the programming, sometimes, it is desirable to skip the current iteration of the loop. In that case, we can use the continue statement in the program. Basically, continue is used to repeat the loop for a specific condition. It skips the following statements a
4 min read
Expandable RecyclerView in Android with Kotlin
In this article, we will get to know how to implement the expandable RecyclerView. In General, we will show the list of items in the listview but in some situations like if you want to show the sub-list items, then we have to use an expandable list. See the below image for a better understanding. Step by Step Implementation 1. If you observe the ab
7 min read
Kotlin Exception Handling | try, catch, throw and finally
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program. There are two types of Exceptions - Checked Exceptio
6 min read
A Complete Guide to Learn Kotlin For Android App Development
Kotlin is a statically typed, cross-platform, general-purpose programming language for JVM developed by JetBrains. This is a language with type inference and fully interoperable with Java. Kotlin is concise and expressive programming as it reduces the boilerplate code. Since Google I/O 2019, Android development has been Kotlin-first. Kotlin is seam
8 min read
Kotlin if-else expression
Decision Making in programming is similar to decision-making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. If the condition is true then it enters into the condi
4 min read
Android - Save ArrayList to SharedPreferences with Kotlin
SharedPreferences is local storage in android which is used to store data in the form of key and value pairs within the android devices. We can store data in the form of key and value pairs using Shared Preferences. In this article, we will take a look at How to Save Array List to SharedPreferences in Android using Kotlin. A sample video is given b
9 min read
Create an Android App that Displays List of All Trending Kotlin git-hub Repositories
Kotlin is a popular programming language that has gained much attention in recent years. It is known for its simplicity, conciseness, and compatibility with existing Java code. GitHub is a popular platform for hosting and sharing code, including Kotlin projects. This article will discuss how to build an application that shows a list of Kotlin GitHu
12 min read
Kotlin Environment setup for Command Line
To set up a Kotlin environment for the command line, you need to do the following steps: Install the Java Development Kit (JDK): Kotlin runs on the Java virtual machine, so you need to have the JDK installed. You can download the latest version from the official Oracle website.Download the Kotlin compiler: You can download the latest version of the
2 min read
Kotlin Environment setup with Intellij IDEA
Kotlin is a statically typed, general-purpose programming language developed by JetBrains that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011. Kotlin is object-oriented language and a better language than Java, but still be fully interoperable with Java code. Let's see how to setu
2 min read
Kotlin Nested class and Inner class
Nested Class In Kotlin, you can define a class inside another class, which is known as a nested class. Nested classes have access to the members (fields and methods) of the outer class. Here is an example of a nested class in Kotlin: C/C++ Code class Car { var make: String var model: String var year: Int inner class Engine { var horsepower: Int = 0
5 min read
Android - Line Graph View with Kotlin
Graphs are used in android applications to display vast amounts of data in an easily readable form. There are different types of graphs used such as BarGraph, GroupBar graph, point, and line graph to represent data. In this article, we will take a look at How to use Line Graph View in Android using Kotlin. A sample video is given below to get an id
3 min read
Working with Anonymous Function in Kotlin
In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas. Although the return type is inferred automatically by the Kotlin compiler in most cases, for cases where it can
3 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.
2 min read
Kotlin Operators
Operators are the special symbols that perform different operation on operands. For example + and - are operators that perform addition and subtraction respectively. Like Java, Kotlin contains different kinds of operators. Arithmetic operatorRelation operatorAssignment operatorUnary operatorLogical operatorBitwise operator Arithmetic Operators - Op
3 min read
Kotlin Standard Input/Output
In this article, we will discuss here how to take input and how to display the output on the screen in Kotlin. Kotlin standard I/O operations are performed to flow sequence of bytes or byte streams from input device such as Keyboard to the main memory of the system and from main memory to output device such as Monitor. In Java, we use System.out.pr
5 min read
Kotlin Expression, Statement and Block
Kotlin Expression - An expression consists of variables, operators, methods calls etc that produce a single value. Like other language, Kotlin expression is building blocks of any program that are usually created to produce new value. Sometimes, it can be used to assign a value to a variable in a program. It is to be noted that an expression can co
4 min read
Kotlin for loop
In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of for loop in Kotlin: for(item in collection) { // code to execute } In Kotlin
4 min read
Kotlin while loop
In programming, loop is used to execute a specific block of code repeatedly until certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of loop you can save time and you need to write only two lines. While loop - It consists of a block of code and a condition. First
2 min read
Kotlin do-while loop
Like Java, do-while loop is a control flow statement which executes a block of code at least once without checking the condition, and then repeatedly executes the block, or not, it totally depends upon a Boolean condition at the end of do-while block. It contrast with the while loop because while loop executes the block only when condition becomes
2 min read
Kotlin Unlabelled break
When we are working with loops and want to stop the execution of loop immediately if a certain condition is satisfied, in this case, we can use either break or return expression to exit from the loop. In this article, we will discuss learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to nea
4 min read
Kotlin labelled break
While working with loops say you want to stop the execution of loop immediately if a certain condition is satisfied. In this case you can use either break or return expression to exit from the loop. In this article, we are going to learn how to use break expression to exit a loop. When break expression encounters in a program it terminates to neare
4 min read
Article Tags :