Sobes.tech
Junior — Middle

What is the main function of named constructors in programming?

sobes.tech AI

Answer from AI

Named constructors allow creating multiple constructors with different names within a single class. This helps in creating objects with different initialization methods, making the code more readable and understandable.

For example, in Dart, you can define named constructors for different ways of creating an object:

class User {
  String name;
  int age;

  User(this.name, this.age);

  User.guest() {
    name = 'Guest';
    age = 0;
  }

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];
}

Here, User.guest() and User.fromJson() are named constructors that create objects with different logic.

What is the main function of named constructors in… - sobes.tech