Junior — Middle
Can you explain how the 'with' operator is used in Dart and what role it plays?
sobes.tech AI
Answer from AI
In the Dart language, the with operator is used to implement mixins — a way to add functionality to a class without inheriting from another class. Using with, a class can "mix in" methods and properties from one or more mixins.
Example of using with:
mixin Logger {
void log(String message) {
print('Log: $message');
}
}
class Person with Logger {
String name;
Person(this.name);
}
void main() {
var p = Person('Alice');
p.log('Hello!'); // Outputs: Log: Hello!
}
Thus, with allows extending the capabilities of a class without resorting to complex inheritance hierarchies.