Constructing the Basics: Kotlin Constructors and Initialization Explained

Understanding Primary Constructors

In Kotlin, a constructor is a special function for creating an instance of a class. The primary constructor is an integral part of the class declaration. It initializes the class with parameters passed to it when an object is created. Here's the full syntax for defining a class with a primary constructor and manually initializing its properties:

Kotlin
class Car constructor(color: String, brand: String, model: String) {
    var color: String = color // Mutable property
    val brand: String = brand // Immutable property
    val model: String = model // Immutable property
}

val myCar = Car("red", "Toyota", "Corolla") // Instance creation
println("My car is a ${myCar.color} ${myCar.brand} ${myCar.model}.") // Prints "My car is a red Toyota Corolla."

// Changing the color of myCar
myCar.color = "blue"
println("After repainting, my car is a ${myCar.color} ${myCar.brand} ${myCar.model}.") // Prints "After repainting, my car is a blue Toyota Corolla."

// Creating another instance for comparison
val myNeighboursCar = Car("blue", "Ford", "Mustang")
println("My neighbour's car is a ${myNeighboursCar.color} ${myNeighboursCar.brand} ${myNeighboursCar.model}.") // Prints "My neighbour's car is a blue Ford Mustang."

In this detailed syntax, we define each property inside the class body and initialize them with the constructor parameters. The use of val for brand and model makes them immutable (read-only), while var for color allows it to be mutable.

Simplifying Property Declaration in Constructors

Kotlin allows for a more concise syntax to declare and initialize properties directly in the primary constructor. This shorthand notation automatically defines the properties with the constructor parameters, eliminating the need for manual property initialization:

Kotlin
// Primary constructor with properties directly defined
class Car(var color: String, val brand: String, val model: String)

fun main() {
    val myCar = Car("red", "Toyota", "Corolla") // Instance creation
    println("My car is a ${myCar.color} ${myCar.brand} ${myCar.model}.") // Prints "My car is a red Toyota Corolla."

    // Demonstrating property mutability
    myCar.color = "blue"
    println("After a color change, my car is a ${myCar.color} ${myCar.brand} ${myCar.model}.") // Prints "After a color change, my car is a blue Toyota Corolla."    
}

This version clearly shows how Kotlin's concise constructor syntax can define and initialize both mutable (var) and immutable (val) properties directly. This approach significantly reduces boilerplate, making your code more readable. Properties declared as val are immutable, meaning once assigned, their values cannot be changed, while var properties are mutable and can be modified.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal