Search⌘ K
AI Features

Constructors

Explore the role of constructors in Kotlin classes, focusing on primary and secondary constructors. Understand how to initialize properties efficiently and use default values to simplify object creation. This lesson helps you grasp constructor usage for robust Kotlin programming.

When we create an object, we often want to initialize it with specific values. This is what we use constructors for. As we’ve seen already, when no constructors are specified, an empty default constructor is generated with no parameters.

Kotlin 1.5
// Simplest class definition
class A
@Suppress("UNUSED_VARIABLE")
fun main() {
// Object creation from a class
val a: A = A()
}

To specify our custom constructor, the classic way is to use the constructor keyword inside the class body and then define its parameters and body.

Kotlin 1.5
class User {
var name: String = ""
var surname: String = ""
constructor(name: String, surname: String) {
this.name = name
this.surname = surname
}
}
fun main() {
val user = User("Johnny", "Depp")
println(user.name) // Johnny
println(user.surname) // Depp
}

Primary

...