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

bookPrimary Constructors

Desliza para mostrar el menú

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?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 1

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 2. Capítulo 1
some-alt