Understanding the Basics of Kotlin Constructors

22 Jul 2023 Balmiki Mandal 0 Kotlin

Understanding the Kotlin Constructors

Kotlin is an object-oriented programming language. As such, it has a variety of constructs used to create objects and define their behavior. One of these constructs is the constructors. A constructor is a special type of function used to initialize the fields of a class or struct when a new instance of that class or struct is created. In this article, we will take a closer look at the different types of constructors in Kotlin.

Primary Constructor

The primary constructor is the most basic form of a constructor. It is defined within the class body, and it is responsible for initializing any parameters declared within the class header. For example:

class Person(name: String) {
    var n = name
}

Here, we have a class called Person with a single parameter declared in the class header. We also have a variable called n where we assign the value of the parameter, name, to. This is the primary constructor. Every time we create an instance of this class, the parameter, name, will be passed in as an argument to the constructor, and the value of n will be set as the value of the parameter. This allows us to store the value of the parameter in the instance.

Secondary Constructor

A secondary constructor is a more specialized form of constructor, and is used when we want to do something more than just assign values to parameters. This can include anything from validating incoming data to setting up class variables. For example:

class Person(name: String) {
    var n = name

    constructor(name: String, age: Int) : this(name) {
        // Do something with the age parameter
    }
}

Here, we have a secondary constructor that takes an additional parameter, age. This constructor calls the primary constructor first, assigning the value of the parameter, name, to the n variable. It then does something with the age parameter. This means that the secondary constructor is able to do something with the data before it is stored in the instance.

Conclusion

Kotlin has two types of constructors: primary constructors and secondary constructors. Primary constructors are the most basic form of constructor and are used to assign values to parameters. Secondary constructors are more specialized, and are used to do something with the parameter values before they are stored in the instance. Understanding how to use constructors in Kotlin is an important part of mastering the language, so it's important to understand them thoroughly.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.