What is a primary constructor in Kotlin?
What is a primary constructor in Kotlin?
A primary constructor in Kotlin is a concise way to initialize a class and its properties. It is part of the class header and goes after the class name, enclosed in parentheses. The primary constructor can have parameters that are used to initialize the class properties.
Here's an example of a class with a primary constructor:
class Person(val name: String, var age: Int) {
// class body
}
In this example, the primary constructor declares two properties: name (read-only) and age (read-write). When an object of the Person class is created, the values passed to the constructor will initialize these properties.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.