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