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

bookSecondary Constructors

Scorri per mostrare il menu

Secondary Constructors in Kotlin

In Kotlin, a class can have a primary constructor and one or more secondary constructors. While the primary constructor is part of the class header and is a concise way to initialize properties, secondary constructors provide additional ways to create objects, often with different parameters or initialization logic.

Why Use Secondary Constructors?

  • To offer alternative ways to create an object when the primary constructor does not cover all use cases;
  • To provide backward compatibility with Java code that expects certain constructors;
  • To handle more complex initialization logic that cannot be handled in the primary constructor;
  • To delegate initialization to another constructor in the same class.

Syntax

A secondary constructor is defined inside the class body using the constructor keyword. Each secondary constructor must delegate to the primary constructor, either directly or indirectly, using the this keyword.

Animal.kt

Animal.kt

copy

When deciding whether to use a secondary constructor, consider if you need to support multiple ways to instantiate your class. In the Animal class example, the primary constructor requires only a name and an age, and sets a default species. The secondary constructor allows you to specify the species as well, giving you flexibility when creating objects. Use secondary constructors if your class needs to support different initialization paths or if you are interoperating with Java code that requires certain constructor signatures. However, when possible, prefer using default parameters in the primary constructor for simplicity.

question mark

When might you use a secondary constructor in Kotlin?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 2. Capitolo 2

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 2
some-alt