Welcome to The Coding College! In this tutorial, we’ll dive into constructors in Kotlin, a core concept that helps initialize objects with specific properties. By the end of this guide, you’ll have a clear understanding of primary and secondary constructors and their use cases in Kotlin.
What Is a Constructor in Kotlin?
A constructor is a special function used to initialize an object when it is created. Kotlin supports two types of constructors:
- Primary Constructor: Declared in the class header and initializes the properties directly.
- Secondary Constructor: Defined inside the class body for additional initialization logic.
Primary Constructor
The primary constructor is concise and integrates directly into the class declaration.
Syntax:
class ClassName(val property1: DataType, var property2: DataType) {
// Class body
}
Example:
class Student(val name: String, var age: Int)
fun main() {
val student = Student("Naman", 24)
println("Name: ${student.name}, Age: ${student.age}")
}
// Output: Name: Naman, Age: 24
Key Points:
- The
val
orvar
keywords are used to declare properties in the primary constructor. val
creates immutable properties, whilevar
creates mutable ones.
Adding Logic with the init
Block
The init
block is used to perform additional initialization logic in the primary constructor.
Example:
class Employee(val name: String, val salary: Int) {
init {
println("Employee Name: $name, Salary: $$salary")
}
}
fun main() {
val employee = Employee("John", 5000)
}
// Output: Employee Name: John, Salary: $5000
Secondary Constructor
The secondary constructor is defined using the constructor
keyword within the class body. It’s often used when multiple initialization paths are needed.
Syntax:
class ClassName {
constructor(parameters) {
// Initialization logic
}
}
Example:
class Car {
var brand: String
var model: String
constructor(brand: String, model: String) {
this.brand = brand
this.model = model
}
fun displayInfo() {
println("Car: $brand $model")
}
}
fun main() {
val car = Car("Tesla", "Model S")
car.displayInfo()
}
// Output: Car: Tesla Model S
Combining Primary and Secondary Constructors
You can use both primary and secondary constructors in a class. However, the secondary constructor must delegate to the primary constructor using the this
keyword.
Example:
class Laptop(val brand: String, val price: Int) {
var isGamingLaptop: Boolean = false
constructor(brand: String, price: Int, isGamingLaptop: Boolean) : this(brand, price) {
this.isGamingLaptop = isGamingLaptop
}
fun displayDetails() {
println("$brand Laptop: $$price, Gaming Laptop: $isGamingLaptop")
}
}
fun main() {
val laptop = Laptop("HP", 1200, true)
laptop.displayDetails()
}
// Output: HP Laptop: $1200, Gaming Laptop: true
Default Values in Primary Constructor
You can provide default values for constructor parameters to simplify object creation.
Example:
class Smartphone(val brand: String = "Generic", val price: Int = 300)
fun main() {
val phone1 = Smartphone()
val phone2 = Smartphone("Samsung", 1000)
println("${phone1.brand} Smartphone: $$${phone1.price}")
println("${phone2.brand} Smartphone: $$${phone2.price}")
}
// Output:
// Generic Smartphone: $300
// Samsung Smartphone: $1000
Kotlin Data Classes and Constructors
When working with data classes, Kotlin automatically generates a primary constructor with properties declared in the class header.
Example:
data class Book(val title: String, val author: String, val price: Double)
fun main() {
val book = Book("Kotlin Basics", "John Doe", 25.99)
println(book)
}
// Output: Book(title=Kotlin Basics, author=John Doe, price=25.99)
Why Learn Kotlin Constructors with The Coding College?
At The Coding College, we prioritize clarity and practicality. Learning constructors empowers you to write more efficient and structured code. With our tutorials, you’ll gain the skills to create scalable applications using Kotlin’s modern features.
Conclusion
Kotlin constructors—both primary and secondary—provide flexible ways to initialize objects. By mastering constructors, you’ll unlock the potential of Kotlin’s object-oriented features and enhance your coding skills.