[Solved] Documentation says "default operator == implementation only considers objects equal if they are identical",why isnt it applied here?

Question

Asked by Be h on December 05, 2021 (source).

    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));
    }

Answer

Question answered by jamesdlin (source).

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 Strings 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.

DART FLUTTER
SHARE: