Reputation: 121
import 'dart:core';
void main() {
String characters = 'World';
String a = 'Hello $characters';
String b = 'Hello $characters';
print(a == b);
Outputs true for equality operator
double x = 3.5;
double y = 3.5;
print(identical(x, y));
print(identical(a, b));
Outputs true in dartpad but false in VS code
List eq3 = const [1, 2, 3];
List eq4 = [1, 2, 3];
print(eq3 == eq4);
print(identical(eq3, eq4));
}
Upvotes: 1
Views: 194
Reputation: 89995
Documentation says "default operator == implementation only considers objects equal if they are identical",why isnt it applied here?
You provide multiple cases, so it's not clear what specific expectations you have that differ from reality.
String characters = 'World'; String a = 'Hello $characters'; String b = 'Hello $characters'; print(a == b);
Outputs true for equality operator
a == b
is true because String
does not use the default operator ==
implementation. String
provides it own override.
double x = 3.5; double y = 3.5; print(identical(x, y)); print(identical(a, b));
Outputs true in dartpad but false in VS code
It's unclear what output you're observing. identical(x, y)
should be true in both environments: x
and y
are both initialized from the same double
literal.
identical(a, b)
returns true when transpiled to JavaScript as an implementation detail. In that situation, Dart String
s are backed by JavaScript strings, and many JavaScript implementations do string interning.
identical(a, b)
might return false
when run through the Dart VM because it can generate separate String
objects. But it also might return true
if you compile a release-mode binary which performs more optimizations.
Ultimately whether identical(a, b)
in your example returns true or not is an implementation detail that you should not rely on.
List eq3 = const [1, 2, 3]; List eq4 = [1, 2, 3]; print(eq3 == eq4); print(identical(eq3, eq4));
You don't say what output you observe (nor what you expect). In this case, List
does not override the default Object.operator ==
. Therefore ==
and identical
will behave, well, identically. Both ==
and identical
will return false
because you necessarily have two different List
objects.
Upvotes: 1
Reputation: 1313
The == operator tests whether two objects are equivalent. Two strings are equivalent if they contain the same sequence of code units. See here.
Edit: You can look back at this answer regarding your third code snippet.
Upvotes: 1