Dart : Copy With Constructor

Dart : Copy With Constructor

·

1 min read

Copy Constructor

  • allows the user to create a new object by copying existing data and modifying selected fields.

class MyClass {
  int value;

  // Regular constructor
  MyClass(this.value);

  // Copy constructor
  MyClass.copy(MyClass original) : value = original.value;
}

void main() {

  var originalObject = MyClass(42);

  var copiedObject = MyClass.copy(originalObject);

  print('Original object: ${originalObject.value}');

  print('Copied object: ${copiedObject.value}');
}

Output

Original object: 42
Copied object: 42

Exited.