Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Primary Constructors | Constructors and Methods
Kotlin Classes and Objects

bookPrimary Constructors

Scorri per mostrare il 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

User.kt

copy

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.

question mark

What is the purpose of a primary constructor in Kotlin?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 2. Capitolo 1
some-alt