In the previous tutorial, we created an object and then assigned values to its properties one by one. This takes up a lot of code.
A much faster and professional way to initialize objects is by using a Constructor. A constructor is a special function that is automatically called the moment an object is created.
In Kotlin, a class can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header—it goes right after the class name.
Syntax:
class ClassName(var property1: DataType, val propertyN: DataType) {
// class body
}
By defining properties directly inside the parentheses (), you instruct Kotlin to create those properties and require values for them whenever a new object is created!
// The constructor creates the brand, model, and year properties automatically! class Car(var brand: String, var model: String, var year: Int)fun main() { // Creating objects and passing values directly into the constructor val car1 = Car("Ford", "Mustang", 1969) val car2 = Car("BMW", "X5", 1999) val car3 = Car("Tesla", "Model S", 2022)
println(car1.brand + " " + car1.model) println(car3.brand + " was made in " + car3.year) }
Notice how much cleaner and shorter this code is compared to assigning properties line-by-line!
Just like regular functions, constructors in Kotlin can have default values. If a default value is provided, you don't have to pass an argument for that property when creating the object.
class Person(var name: String, var age: Int = 18)fun main() { // We provide both name and age val person1 = Person("Alice", 25)
// We only provide name. Age defaults to 18! val person2 = Person("Bob")
println(person1.name + " is " + person1.age) println(person2.name + " is " + person2.age) }
init BlockSometimes, you need to execute some logic or code the moment an object is created (like printing a welcome message or validating data).
Because the primary constructor sits in the class header, it cannot contain actual code. To write initialization logic, you use the init block.
The init block is executed immediately after the primary constructor.
class User(var username: String, var email: String) {
// This block runs automatically when the object is created
init {
println("New user registered!")
println("Username: $username")
println("Email: $email")
println("-------------------")
}
}
fun main() {
val u1 = User("JohnDoe", "john@test.com")
val u2 = User("JaneSmith", "jane@test.com")
}
Kotlin also allows you to create Secondary Constructors using the constructor keyword inside the class body. This is useful if you want to provide multiple ways to initialize an object.
However, if a class has a primary constructor, every secondary constructor must delegate to the primary constructor using the this keyword.
class Pet(var name: String, var type: String) {
// Secondary constructor
constructor(name: String) : this(name, "Unknown") {
println("Secondary constructor called for $name")
}
}
fun main() {
// Calls primary constructor
val p1 = Pet("Buddy", "Dog")
// Calls secondary constructor (which defaults type to "Unknown")
val p2 = Pet("Whiskers")
println(p1.name + " is a " + p1.type)
println(p2.name + " is a " + p2.type)
}
Pro Tip: In modern Kotlin, secondary constructors are rarely used. Using a primary constructor with default values (as shown in section 2) is almost always a cleaner and more preferred approach!
Where is the primary constructor defined in a Kotlin class?
Which block of code is automatically executed right after the primary constructor?