Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"with" keyword in Dart

Tags:

dart

Could somebody please write some formal definition of keyword with in Dart?

In official Dart examples I have only found:

class TaskElement extends LIElement with Polymer, Observable {

But I still can't understand what is it exactly doing.

like image 313
romanos Avatar asked Feb 10 '14 16:02

romanos


People also ask

What is with keyword in Dart?

The with keyword indicates the use of a "mixin". See here. A mixin refers to the ability to add the capabilities of another class or classes to your own class, without inheriting from those classes. The methods of those classes can now be called on your class, and the code within those classes will execute.

What is difference between with and extends in Dart?

It is similar to the reuse you get from extending a class, but is not multiple inheritances. There still only exists one superclass. With is used to include Mixins. A mixin is a different type of structure, which can only be used with the keyword with.

What does ~/ mean in Dart?

~/ Divide, returning an integer result. and ~/= integer division and assignment.

Which is not the keyword in the Dart?

Unlike Java, Dart doesn't have the keywords public , protected , and private . If an identifier starts with an underscore ( _ ), it's private to its library. For details, see Libraries and visibility.


2 Answers

The with keyword indicates the use of a "mixin". See here.

A mixin refers to the ability to add the capabilities of another class or classes to your own class, without inheriting from those classes. The methods of those classes can now be called on your class, and the code within those classes will execute. Dart does not have multiple inheritance, but the use of mixins allows you to fold in other classes to achieve code reuse while avoiding the issues that multiple inheritance would cause.

I note that you have answered some questions about Java -- in Java terms, you can think of a mixin as an interface that lets you not merely specify that a given class will contain a given method, but also provide the code for that method.

like image 164
Jacob Mattison Avatar answered Oct 18 '22 23:10

Jacob Mattison


You can think mixin as Interface in Java and like protocol in Swift.Here is the simple example.

mixin Human {
  String name;
  int age;

  void about();
}

class Doctor with Human {
  String specialization;
  Doctor(String doctorName, int doctorAge, String specialization) {
    name = doctorName;
    age = doctorAge;
    this.specialization = specialization;
  }

  void about() {
    print('$name is $age years old. He is $specialization specialist.');
  }
}


void main() {
  Doctor doctor = Doctor("Harish Chandra", 54, 'child');
  print(doctor.name);
  print(doctor.age);
  doctor.about();
}

Hope it help to understand.

like image 18
Yogendra Singh Avatar answered Oct 18 '22 22:10

Yogendra Singh