0

I have recently jumped to dart after learning core java. Using the similar concept of java, I have tried creating an object of the class 'Product' using the new keyword to which dart warned "Unnecessary new keyword".

void main() {
 Product oil = new Product('sunflower', 2, 300);
 final noodles = Product('waiwai', 20, 20); //name, qty, price
}

So, my question is what advantageous is it for us to omit new in dart and if there are still any situations where using new keyword is absolutely necessary since it is not completely omitted?

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • 1
    https://stackoverflow.com/questions/50091389/do-you-need-to-use-the-new-keyword-in-dart this is answer your question? – Sayyid J Jan 21 '22 at 04:45
  • 1
    Does this answer your question? [Do you need to use the "new" keyword in Dart?](https://stackoverflow.com/questions/50091389/do-you-need-to-use-the-new-keyword-in-dart) – Bhavin Jan 21 '22 at 04:45
  • @Bhavin To some extent, yes but what I also want to know is if omitting the `new` works just as fine, why is it not completely removed? Also, I could see a comment saying "The Dart team had to retract a bit for now and there are some situations where new or const are still required (I don't remember examples or rules)." So, I am hoping to learn with example too. – Kalash Babu Acharya Jan 21 '22 at 04:55
  • 2
    It wasn't removed because that would break existing Dart code. `new` is never required. (`const` is a different story.) – jamesdlin Jan 21 '22 at 05:28
  • 1
    There is a feature as of dart 2.15 (https://medium.com/dartlang/dart-2-15-7e7a598e508a) called constructor tear-offs, which allows you to refer to the default constructor of your class with `Product.new`. This is essentially a method named `new` rather than the `new` keyword, but in any case a constructor tear-off is the only place you should use `new`. – mmcdon20 Jan 21 '22 at 05:33

1 Answers1

2

The advantageous of omitting new is one doesn't need to write redundant letters and can safe the time. The Dart compiler can differentiate the object creating from another.

But there is one place in Dart where you still need new - tear-offs constructor. For example:

void main(List<String> args) {
  boxPutter(Box.new); // new style with tear-offs constructor
  boxPutter((something) => Box(something)); // old style
}

class Box {
  Box(this.staff);
  final int staff;

  @override
  String toString() => 'Box($staff)';
}

void boxPutter(Box Function(int something) constructor) {
  final staffGenerator = 10;
  print(constructor(staffGenerator));
}
Cyrax
  • 688
  • 6
  • 12