Kotlin Constructors

Kotlin Constructors

In Kotlin, constructors are special blocks used to initialize objects.
Kotlin provides two types of constructors:

  1. Primary Constructor

  2. Secondary Constructor

Kotlin constructors are simpler and more powerful than Java.


1. Primary Constructor (Most Important)

The primary constructor is defined in the class header.

Basic Example

class Person(name: String, age: Int)

This only defines parameters, not properties.


Primary Constructor with Properties

Use val or var to create class properties.

class Person(val name: String, var age: Int)

Usage:

val p = Person("Sanjit", 22)
println(p.name)

2. init Block

The init block runs immediately after the primary constructor.

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

➡ Multiple init blocks are allowed (executed top to bottom).


3. Primary Constructor with Default Values

class User(val name: String = "Guest", val age: Int = 0)

Usage:

val u1 = User()
val u2 = User("Rahul")
val u3 = User("Amit", 25)

4. Secondary Constructor

Secondary constructors are defined using the constructor keyword.

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
}
}


5. Calling Primary Constructor from Secondary Constructor

If a class has a primary constructor, all secondary constructors must call it.

class Person(val name: String) {

var age: Int = 0

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

this(name) calls the primary constructor.


6. Constructor with Visibility Modifiers

class Secret private constructor(val code: Int)

Usage:

// Cannot create object from outside the class

Useful for:

  • Singleton patterns

  • Factory methods


7. Constructor with Annotations

class User @JvmOverloads constructor(
val name: String,
val age: Int = 18
)

Useful for Java interoperability.


8. Order of Initialization (Very Important)

Order:

  1. Property initializers

  2. init blocks

  3. Secondary constructor body

class Test(val x: Int) {
val y = x + 1

init {
println("Init block")
}

constructor(x: Int, z: Int) : this(x) {
println("Secondary constructor")
}
}


9. Constructor vs init Block

Constructorinit Block
Takes parametersExecutes logic
One primaryMultiple allowed
Defines propertiesValidation / setup

10. Real-World Example

class BankAccount(val holder: String, balance: Int) {

var balance: Int = balance
private set

init {
require(balance >= 0) { "Balance cannot be negative" }
}
}


Summary

  • Primary constructor is preferred

  • Use init for initialization logic

  • Secondary constructors are optional

  • Kotlin reduces constructor boilerplate

  • Clean & readable object initialization

You may also like...