Kotlin Constructors
Constructors are special member functions that are called when an object of a class is created. They initialize the properties of a class and set up the object's initial state. In Kotlin, constructors are more flexible and powerful than in many other languages, offering a variety of ways to define how objects are created.
Understanding Constructors in Kotlin
Kotlin provides two types of constructors:
- Primary Constructor
- Secondary Constructor(s)
Additionally, Kotlin offers initialization blocks (init
) that work alongside constructors to initialize objects.
Let's explore each of these concepts in detail.
Primary Constructor
The primary constructor is part of the class header and appears right after the class name. It's a concise way to define a constructor and class properties in a single declaration.
Basic Syntax
class Person(val name: String, var age: Int)
In this simple example:
name
is a read-only property (defined withval
)age
is a mutable property (defined withvar
)- Both are automatically created as properties of the class
Example with Primary Constructor
class Student(val name: String, var grade: Int) {
fun displayInfo() {
println("Student: $name, Grade: $grade")
}
}
fun main() {
val student = Student("Alex", 10)
student.displayInfo()
}
Output:
Student: Alex, Grade: 10
Primary Constructor with Initialization Block
If you need to execute code during initialization, you can use the init
block:
class Employee(val name: String, val position: String) {
val fullDetails: String
init {
println("Initializing a new Employee")
fullDetails = "$name - $position"
}
}
fun main() {
val emp = Employee("Jane Doe", "Software Developer")
println(emp.fullDetails)
}
Output:
Initializing a new Employee
Jane Doe - Software Developer
You can have multiple init
blocks, and they execute in the order they appear in the class body, interspersed with property initializers.
Secondary Constructors
Secondary constructors provide alternative ways to create objects of a class. They are defined using the constructor
keyword.
Syntax
class Person(val name: String) {
var age: Int = 0
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
Example with Secondary Constructor
class User(val username: String) {
var email: String = ""
var isPremium: Boolean = false
constructor(username: String, email: String) : this(username) {
this.email = email
}
constructor(username: String, email: String, isPremium: Boolean) : this(username, email) {
this.isPremium = isPremium
}
fun displayInfo() {
println("Username: $username")
println("Email: ${if(email.isEmpty()) "Not provided" else email}")
println("Account type: ${if(isPremium) "Premium" else "Standard"}")
println("-----------------------")
}
}
fun main() {
val user1 = User("john_doe")
val user2 = User("jane_doe", "[email protected]")
val user3 = User("premium_user", "[email protected]", true)
user1.displayInfo()
user2.displayInfo()
user3.displayInfo()
}
Output:
Username: john_doe
Email: Not provided
Account type: Standard
-----------------------
Username: jane_doe
Email: [email protected]
Account type: Standard
-----------------------
Username: premium_user
Email: [email protected]
Account type: Premium
-----------------------