Constructors
In this page:
class ClassName(val property: Type, param: Type) { // primary constructor
constructor(other: Type) : this(other, defaultValue) {
// secondary constructor
}
}
The Primary Constructor
The primary constructor is part of the class header itself, listing the parameters needed to build an instance directly after the class name.
Example: The Primary Constructor
// Define a class `Book`
class Book(val title: String, val author: String)
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `book`, set to `Book("Kotlin in Action", "Dmitry Jemerov")`
val book = Book("Kotlin in Action", "Dmitry Jemerov")
// Print "${book.title} by ${book.author}" to the console, with a trailing newline
println("${book.title} by ${book.author}")
}
Login to try C/C++/Java/PHP code in the editor
Secondary Constructors
A constructor keyword inside the class body defines an alternate way to build an instance; every secondary constructor must eventually delegate to the primary constructor using : this(...).
Example: Secondary Constructors
// Define a class `Book`
class Book(val title: String, val author: String) {
constructor(title: String) : this(title, "Unknown")
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `book`, set to `Book("Kotlin Basics")`
val book = Book("Kotlin Basics")
// Print "${book.title} by ${book.author}" to the console, with a trailing newline
println("${book.title} by ${book.author}")
}
Login to try C/C++/Java/PHP code in the editor
Constructor Parameters vs Properties
A parameter listed without val/var in the primary constructor is only available inside the constructor and any init blocks -- to expose it as a member, it must be declared as val or var, or explicitly assigned to a property.
Example: Constructor Parameters vs Properties
// Define a class `Circle`
class Circle(radius: Double) {
// Declare a read-only variable `area` (a Double), set to `Math.PI * radius * radius`
val area: Double = Math.PI * radius * radius
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `circle`, set to `Circle(2.0)`
val circle = Circle(2.0)
// Print "Area: ${circle.area}" to the console, with a trailing newline
println("Area: ${circle.area}")
}
Login to try C/C++/Java/PHP code in the editor
Default Values in Constructors
Just like regular functions, constructor parameters can have default values, letting some arguments be omitted when creating an instance.
Example: Default Values in Constructors
// Define a class `User`
class User(val name: String, val role: String = "member")
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `admin`, set to `User("Ana", "admin")`
val admin = User("Ana", "admin")
// Declare a read-only variable `user`, set to `User("Bo")`
val user = User("Bo")
// Print "${admin.name}: ${admin.role}" to the console, with a trailing newline
println("${admin.name}: ${admin.role}")
// Print "${user.name}: ${user.role}" to the console, with a trailing newline
println("${user.name}: ${user.role}")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting that a secondary constructor must delegate to the primary constructor with
: this(...)when a primary constructor exists. - Duplicating validation logic across multiple secondary constructors instead of putting shared setup in the primary constructor or an
initblock. - Confusing constructor parameters with properties; a plain parameter (no
val/var) is not accessible outside the constructor unless stored.
- The primary constructor is declared in the class header, right after the class name.
- Secondary constructors are declared with the
constructorkeyword inside the class body and must delegate to the primary constructor. - Constructor parameters without
val/varare only usable inside the constructor/init block, not as class members. - Multiple secondary constructors let a class be created in different ways while sharing common setup logic.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: