Kotlin Constructors: Primary, Secondary and init Blocks

Kotlin course · Object-oriented programming · Lesson 34 of 51

A constructor is the code that runs when you create an object. In Kotlin, most classes need only one short line to declare their constructor and properties together.

Primary constructor

The primary constructor goes right after the class name. Writing val or var turns a parameter into a property:

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

fun main() {
    val user = User("Asha", 25)
    println(user.name)
    user.age = 26
    println(user.age)
}

Output:

Asha
26
ParameterBecomes
val name: Stringread-only property
var age: Intchangeable property
name: String (no val/var)just a constructor parameter, not stored

Default values

Constructor parameters can have defaults, just like function parameters, and you can use named arguments:

class Account(val owner: String, val balance: Double = 0.0, val currency: String = "INR")

fun main() {
    val a = Account("Ravi")
    val b = Account("Meera", 5000.0)
    val c = Account("Kabir", currency = "USD")
    println("${a.owner} ${a.balance} ${a.currency}")
    println("${b.owner} ${b.balance} ${b.currency}")
    println("${c.owner} ${c.balance} ${c.currency}")
}

Output:

Ravi 0.0 INR
Meera 5000.0 INR
Kabir 0.0 USD

Default values mean you rarely need more than one constructor in Kotlin.

init blocks

Put code that should run when the object is created in an init block. It can use the constructor parameters:

class Rectangle(val width: Int, val height: Int) {
    val area: Int

    init {
        println("Creating a ${width}x$height rectangle")
        area = width * height
    }
}

fun main() {
    val r = Rectangle(4, 5)
    println("Area: ${r.area}")
}

Output:

Creating a 4x5 rectangle
Area: 20

Validating input with require

class Product(val name: String, val price: Int) {
    init {
        require(name.isNotBlank()) { "Name must not be blank" }
        require(price >= 0) { "Price can't be negative: $price" }
    }
}

fun main() {
    println(Product("Mouse", 599).name)
    try {
        Product("Cable", -10)
    } catch (e: IllegalArgumentException) {
        println("Error: ${e.message}")
    }
}

Output:

Mouse
Error: Price can't be negative: -10

require throws an IllegalArgumentException with your message when the condition is false. You’ll learn more about try/catch in the exception handling lesson.

Properties in the class body

Not every property needs to come from the constructor:

class Order(val id: Int, val items: List<String>) {
    val itemCount = items.size
    var status = "Placed"
    val createdAt = "2026-11-24"
}

fun main() {
    val order = Order(101, listOf("Tea", "Biscuits"))
    order.status = "Shipped"
    println("#${order.id}: ${order.itemCount} items, ${order.status}")
}

Output:

#101: 2 items, Shipped

Secondary constructors

A secondary constructor is declared with constructor inside the class. If there’s a primary constructor, every secondary one must call it with this(...):

class Temperature(val celsius: Double) {
    constructor(fahrenheit: Int) : this((fahrenheit - 32) / 1.8)
}

fun main() {
    println(Temperature(25.0).celsius)
    println(Temperature(212).celsius)
}

Output:

25.0
100.0

In practice, default values or a factory function in a companion object are usually clearer than secondary constructors. You’ll meet companion objects later in this module.

Order of initialization

Property initializers and init blocks run from top to bottom, in the order they appear in the class:

class Demo(name: String) {
    val first = "First: $name".also { println(it) }
    init { println("init block") }
    val second = "Second: ${name.length}".also { println(it) }
}

fun main() {
    Demo("Kotlin")
}

Output:

First: Kotlin
init block
Second: 6

Private constructor

Make the constructor private when objects should only be created in a controlled way:

class Email private constructor(val value: String) {
    companion object {
        fun of(text: String): Email? =
            if ("@" in text) Email(text.trim().lowercase()) else null
    }
}

fun main() {
    println(Email.of("  Asha@Example.com ")?.value)
    println(Email.of("not-an-email"))
}

Output:

asha@example.com
null

Common mistakes

  • Forgetting val/var: class User(name: String) doesn’t store name, so user.name doesn’t compile.
  • Using a property before it’s initialized: an init block can’t read a property that is declared below it. Kotlin reports a compile error.
  • Writing many secondary constructors: use default values instead.

Exercise

Create a BankAccount class with an owner, an opening balance that defaults to 0 and must not be negative, and a deposit function.

class BankAccount(val owner: String, openingBalance: Double = 0.0) {
    var balance = openingBalance
        private set

    init {
        require(openingBalance >= 0) { "Opening balance can't be negative" }
    }

    fun deposit(amount: Double) {
        require(amount > 0) { "Deposit must be positive" }
        balance += amount
    }
}

fun main() {
    val acc = BankAccount("Zoya")
    acc.deposit(1500.0)
    acc.deposit(250.0)
    println("${acc.owner}: ₹${acc.balance}")
}

Output:

Zoya: ₹1750.0

private set means other code can read balance but only the class itself can change it.

FAQ

What is a primary constructor in Kotlin?

The constructor declared in the class header: class User(val name: String). With val/var, its parameters become properties.

What is the init block used for?

Code that should run when an object is created, such as validation or computing other properties.

Do I need secondary constructors in Kotlin?

Rarely. Default parameter values cover most cases where Java needs several constructors.

WhatsApp us📞 Call now