English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Constructor (Constructor)

In this article, you will learn about constructors in Kotlin (primary and secondary constructors) and initialization blocks with the help of examples.

Constructors are a concise way to initialize class properties.

It is a special member function that is called when an instance (object) is instantiated (created). However, they work slightly differently in Kotlin.

In Kotlin, there are two constructors:

  • Primary constructor - A concise way to initialize a class

  • Secondary constructor - Allows you to place other initialization logic

Primary constructor

The primary constructor is part of the class header. Here is an example:

class Person(val firstName: String, var age: Int) {
    // class body
}

The code block enclosed in parentheses is the primary constructor: (val firstName: String, var age: Int).

The constructor declaration defines two properties: firstName (a read-only property because it is declared with the keyword val) and age (a read-write property because it is declared with the keyword var).

Example: Primary Constructor

fun main(args: Array<String>) {
    val person1 = Person("Joe", 25)
    println("First Name = ${person1.firstName}")
    println("Age = ${person1.age")
}
class Person(val firstName: String, var age: Int) {
}

When running the program, the output is:

First Name = Joe
Age = 25

When creating an object of the Person class, the values Joe and 25As if Person is a function.

This will initialize person1 The firstName and age properties of the object are initialized to "Joe" and 25.

There are other ways to use the primary constructor.

Primary constructor and initialization block

The syntax of the primary constructor is constrained and cannot contain any code.

To place initialization code (not just initialization property code), an initialization block is used. It is prefixed with the init keyword. Let's modify the above example with an initialization statement block:

fun main(args: Array<String>) {
    val person1 = Person("joe", 25)
}
class Person(fName: String, personAge: Int) {
    val firstName: String
    var age: Int
    //Initialization block
    init {
        firstName = fName.capitalize()
        age = personAge
        println("First Name = $firstName")
        println("Age = $age")
    }
}

When running the program, the output is:

First Name = Joe
Age = 25

Here, when creating person1object, the parameters fName and personAge inside the parentheses respectively accept the values "Joe" and 25However, when using fName and personAge, var or val is not used, and they are not properties of the Person class.

The Person class declares two properties firstName and age.

When creating a person1The object is created, and the code inside the initialization block is executed. The initialization block not only initializes its properties but also prints them out.

This is another way to perform the same task:

fun main(args: Array<String>) {
    val person1 = Person("joe", 25)
}
class Person(fName: String, personAge: Int) {
    val firstName: fName.capitalize()
    var age: personAge
    //Initialization block
    init {
        println("First Name = $firstName")
        println("Age = $age")
    }
}

To distinguish between constructor parameters and properties, different names are used (fName and FirstName, as well as Personage and age). For constructor parameters, it is more common to use _firstName and _age, rather than completely different names. For example:

class Person(_firstName: String, _age: Int) {
    val firstName: _firstName.capitalize()
    var age: _age
    // Initialization block
    init {
        ... .. ...
    }
}

Default values in the primary constructor

You can provide default values for constructor parameters (similar to providingDefault parameters)。For example:

fun main(args: Array<String>) {
    println("person"1 is instantiated)
    val person1 = Person("joe", 25)
    println("person"2 is instantiated)
    val person2 = Person("Jack")
    println("person"3 is instantiated)
    val person3 = Person()
}
class Person(_firstName: String = "UNKNOWN", _age: Int = 0) {
    val firstName: _firstName.capitalize()
    var age: _age
    //Initialization block
    init {
        println("First Name = $firstName")
        println("Age = $age\n")
    }
}

When running the program, the output is:

First Name = Joe
Age = 25
person2 is instantiated
First Name = Jack
Age = 0
person3 is instantiated
First Name = UNKNOWN
Age = 0

Kotlin Secondary Constructor

In Kotlin, a class can also contain one or more secondary constructors. They are created using the constructor keyword.

Secondary constructors are not common in Kotlin. The most common use case for secondary constructors appears when you need to extend a class that provides multiple constructors to initialize the class in different ways. Before learning, please confirm that you have understoodKotlin Inheritance.

You can create secondary constructors in Kotlin as follows:

class Log {
    constructor(data: String) {
        // Some code
    }
    constructor(data: String, numberOfData: Int) {
        // Some code
    }
}

Here, the Log class has two secondary constructors but no primary constructor.

You can extend the class as follows:

class Log {
    constructor(data: String) {
        // Code
    }
    constructor(data: String, numberOfData: Int) {
        // Code
    }
}
class AuthLog: Log {
    constructor(data: String): super(data) {
        // Code
    }
    constructor(data: String, numberOfData: Int): super(data, numberOfData) {
        // Code
    }
}

Here, the constructor of the derived class AuthLog calls the corresponding constructor of the base class Log. To do this, use super().

In Kotlin, you can also use this() to call another constructor of the same class (like in Java).

class AuthLog: Log {
    constructor(data: String): this(data, 10) {
        // Code
    }
    constructor(data: String, numberOfData: Int): super(data, numberOfData) {
        // Code
    }
}

Example: Kotlin Secondary Constructor

fun main(args: Array<String>) {
    val p1 = AuthLog("Bad Password")
}
open class Log {
    var data: String = ""
    var numberOfData = 0
    constructor(_data: String) {
    }
    constructor(_data: String, _numberOfData: Int) {
        data = _data
        numberOfData = _numberOfData
        println("$data: $numberOfData times")
    }
}
class AuthLog: Log {
    constructor(_data: String): this("From AuthLog -> " + _data, 10) {
    }
    constructor(_data: String, _numberOfData: Int): super(_data, _numberOfData) {
    }
}

When running the program, the output is:

From AuthLog -> Bad Password: 10 times

Note:If a class does not have a primary constructor, the secondary constructor must initialize the base class or delegate to another constructor (as shown in the example above).