Kotlin Constructors
Initializing objects when they are created
🏗️ What are Constructors?
Constructors in Kotlin are special functions that initialize objects when they're created. They set up initial values and prepare the object for use, like setting up a new house before moving in.
// Primary constructor in class header
class Person(name: String, age: Int) {
val personName = name
val personAge = age
fun introduce() {
println("Hi, I'm $personName, age $personAge")
}
}
Usage:
val person = Person("Alice", 25)
person.introduce() // Hi, I'm Alice, age 25
Key Constructor Concepts
Primary Constructor
Main constructor in class header
class Car(brand: String)
Secondary Constructor
Additional constructors in class body
constructor(name: String) { }
Init Block
Code that runs during initialization
init { println("Created!") }
Default Values
Parameters with default values
class User(name: String = "Guest")
🔹 Primary Constructor
The primary constructor is part of the class header and can declare properties directly:
// Primary constructor with property declarations
class Student(val name: String, val grade: Int, var gpa: Double) {
// Init block runs when object is created
init {
println("New student created: $name")
if (gpa > 4.0) {
println("Warning: GPA cannot exceed 4.0")
gpa = 4.0
}
}
fun displayInfo() {
println("Student: $name, Grade: $grade, GPA: $gpa")
}
}
fun main() {
val student1 = Student("John", 10, 3.8)
val student2 = Student("Sarah", 11, 4.5) // GPA will be corrected
student1.displayInfo()
student2.displayInfo()
}
Output:
New student created: John
New student created: Sarah
Warning: GPA cannot exceed 4.0
Student: John, Grade: 10, GPA: 3.8
Student: Sarah, Grade: 11, GPA: 4.0
🔹 Secondary Constructors
Additional constructors that provide different ways to create objects:
class Book(val title: String, val author: String, val pages: Int) {
// Secondary constructor with fewer parameters
constructor(title: String, author: String) : this(title, author, 0) {
println("Book created without page count")
}
// Secondary constructor with just title
constructor(title: String) : this(title, "Unknown Author", 0) {
println("Book created with minimal info")
}
fun displayInfo() {
println("'$title' by $author ($pages pages)")
}
}
fun main() {
val book1 = Book("1984", "George Orwell", 328)
val book2 = Book("Animal Farm", "George Orwell")
val book3 = Book("Mystery Novel")
book1.displayInfo()
book2.displayInfo()
book3.displayInfo()
}
Output:
Book created without page count
Book created with minimal info
'1984' by George Orwell (328 pages)
'Animal Farm' by George Orwell (0 pages)
'Mystery Novel' by Unknown Author (0 pages)
🔹 Default Parameter Values
Provide default values to make constructors more flexible:
class Rectangle(
val width: Double = 1.0,
val height: Double = 1.0,
val color: String = "white"
) {
init {
println("Created a $color rectangle: ${width}x$height")
}
fun area(): Double {
return width * height
}
fun displayInfo() {
println("Rectangle: ${width}x$height, Color: $color, Area: ${area()}")
}
}
fun main() {
val rect1 = Rectangle() // All defaults
val rect2 = Rectangle(5.0) // Width specified
val rect3 = Rectangle(3.0, 4.0) // Width and height
val rect4 = Rectangle(2.0, 3.0, "blue") // All specified
val rect5 = Rectangle(color = "red", width = 6.0) // Named parameters
rect1.displayInfo()
rect2.displayInfo()
rect3.displayInfo()
rect4.displayInfo()
rect5.displayInfo()
}
Output:
Created a white rectangle: 1.0x1.0
Created a white rectangle: 5.0x1.0
Created a white rectangle: 3.0x4.0
Created a blue rectangle: 2.0x3.0
Created a red rectangle: 6.0x1.0
Rectangle: 1.0x1.0, Color: white, Area: 1.0
Rectangle: 5.0x1.0, Color: white, Area: 5.0
Rectangle: 3.0x4.0, Color: white, Area: 12.0
Rectangle: 2.0x3.0, Color: blue, Area: 6.0
Rectangle: 6.0x1.0, Color: red, Area: 6.0