Primary Constructors
Glissez pour afficher le menu
Introduction to constructors
When you create a class in Kotlin, you often need a way to set up its initial state. This is where constructors come in. Constructors allow you to provide values when you create an object, ensuring that all necessary properties are initialized.
What is a Constructor?
A constructor is a special function that runs when you create an instance of a class. Its main job is to set up the object's properties with initial values. In Kotlin, you can define constructors directly in the class header or inside the class body.
Primary Constructor Syntax
The primary constructor is the main way to declare and initialize properties for a class in Kotlin. You define it in the class header, right after the class name, using parentheses. The parameters you add here can be used to initialize properties, making your class concise and readable.
User.kt
In the User class above, the primary constructor takes two parameters: name and age. By declaring them with val, you automatically create read-only properties for each parameter. When you create a new User object with User("Alice", 30), the primary constructor assigns "Alice" to name and 30 to age. This approach makes it easy to ensure that every User object has its essential properties initialized from the start.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion