Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
keyword
communitycreator

What is the new keyword in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The new keyword is used to create an instance of a class. However, Dart 2 makes the new keyword optional. Calling a class will always return a new instance of that class.

Syntax

class class_name = new class_name( [arguments]);

Example

class Person {
  // some code
 }

void main() {
    Person person = new Person();
}

In Dart 2, using the new keyword is optional. The code above can be written as the following:

class Person {
  // some code
 }

void main() {
    Person person =  Person();
}

Let's look at the code below to further understand:

class Person {
// class properties
String firstName = 'Maria';
String lastName = 'Elijah';
// class method
void display() {
print('My name is $firstName $lastName');
}
}
void main() {
// Creating an object of class Person
Person person = new Person();
// invoke class method using its instance
person.display();
}

Explanation

  • Lines 1–10: We create a class, Person, which has the properties, firstName and lastName. Next we create a method, display().

  • Lines 12: We create a main() function.

  • Line 14: We create an object of class Person named person.

  • Line 16: We invoke the class method, display(), using person.

RELATED TAGS

dart
keyword
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring