Dart, a powerful programming language, brings to the table a plethora of operators that serve different purposes. This article aims to explore these operators, delineating their associativity and precedence, and providing practical examples of their use.
Overview
Dart's operators can be grouped into various categories including arithmetic, relational, logical, bitwise, shift, conditional, cascade, and more. Let's delve into each of these categories to understand their functionality.
1. Unary Operators
These are operators that act on a single operand. They can be divided into:
a. Unary Postfix:
expr++ expr-- () [] ?[] . ?. !
Associativity: None
b. Unary Prefix:
-expr !expr ~expr ++expr --expr await expr
Associativity: None
2. Arithmetic Operators
These operators are used for mathematical operations. They include:
a. Multiplicative:
* / % ~/
Associativity: Left
b. Additive:
+ -
Associativity: Left
Here's an example of arithmetic operators in action:
assert(2 + 3 == 5);
assert(2 * 3 == 6);
3. Shift Operators
These operators shift the bits of their operand.
<< >> >>>
Associativity: Left
4. Bitwise Operators
Used to manipulate individual bits:
& ^ |
Associativity: Left
5. Relational and Type Test Operators
For comparison and type checks:
>= > <= < as is is!
Associativity: None
6. Equality Operators
These are for equality checks:
== !=
Associativity: None
7. Logical Operators
Logical AND and OR:
&& ||
Associativity: Left
8. Conditional Operators
These include the standard ternary operator:
expr1 ? expr2 : expr3
Associativity: Right
9. Cascade Notation
A way to make a sequence of operations on the same object:
.. ?..
Associativity: Left
10. Assignment Operators
These include standard and compound assignments:
= *= /= += -= &= ^= etc.
Associativity: Right
Special Considerations
The above table should be used as a guide, but for authoritative behavior, consult Dart's language specification.
Precedence Example
In Dart, higher-precedence operators execute before lower-precedence ones:
if (n % i == 0 && d % i == 0) ...
Type Test Operators
as
, is
, and is!
operators are handy for checking types:
if (employee is Person) {
employee.firstName = 'Bob';
}
Cascade Notation
Cascades allow a sequence of operations on the same object:
var paint = Paint()
..color = Colors.black
..strokeCap = StrokeCap.round;
Other Operators
Other operators like function application ()
, subscript access []
, conditional subscript access ?[]
, and member access .
are essential as well.
Conclusion
Dart offers an extensive set of operators, each with a distinct purpose. The above guide is intended to serve as a comprehensive reference for Dart developers seeking to understand and implement these operators effectively.
By familiarizing themselves with the syntax and usage of these operators, developers can write concise and efficient code. The Dart language specification should be referred to for the most authoritative and detailed information on this subject.