Constructors
In this page:
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
class Book(val title: String, val author: String)
fun main() {
val book = Book("Kotlin in Action", "Dmitry Jemerov")
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
class Book(val title: String, val author: String) {
constructor(title: String) : this(title, "Unknown")
}
fun main() {
val book = Book("Kotlin Basics")
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
class Circle(radius: Double) {
val area: Double = Math.PI * radius * radius
}
fun main() {
val circle = Circle(2.0)
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
class User(val name: String, val role: String = "member")
fun main() {
val admin = User("Ana", "admin")
val user = User("Bo")
println("${admin.name}: ${admin.role}")
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: