Sobes.tech
Junior — Middle

Can you list different types of constructors used in Kotlin classes?

sobes.tech AI

Answer from AI

In Kotlin, there are two main types of constructors in classes:

  1. Primary constructor — declared in the class header after the class name. It can accept parameters and initialize class properties.
class Person(val name: String, var age: Int)
  1. Secondary constructors — declared inside the class body using the constructor keyword. They are used if you need to provide additional initialization options.
class Person {
    var name: String
    var age: Int

    constructor(name: String) {
        this.name = name
        this.age = 0
    }

    constructor(name: String, age: Int) {
        this.name = name
        this.age = age
    }
}

It is also worth noting that the primary constructor can be empty, and property initialization can occur in the init block.

class Person(val name: String) {
    var age: Int = 0

    init {
        println("Person created: $name")
    }
}