Sobes.tech
Junior

How does comparison using the identical operator work in Dart?

sobes.tech AI

Answer from AI

The identical(a, b) operator in Dart returns true if its arguments a and b are the same object in memory. Otherwise, it returns false.

This differs from using the == operator, which can be overridden by classes to define logical equality rather than object identity.

Examples:

// Object A
var list1 = [1, 2, 3];
// Object B (another object in memory)
var list2 = [1, 2, 3];

print(identical(list1, list2)); // false (different objects)
print(list1 == list2);         // true (logically equal if List overrides ==)

// Object C, a reference to the same object as list1
var list3 = list1;

print(identical(list1, list3)); // true (refers to the same object)

For primitive types (numbers, strings, booleans, null), which are immutable, the identical operator often behaves the same as ==, since Dart may cache or reuse instances of immutable values.

var a = 10;
var b = 10;
print(identical(a, b)); // true (Dart likely uses the same instance for the value 10)

var s1 = "hello";
var s2 = "hello";
print(identical(s1, s2)); // true (Dart caches string literals)

The main use of identical is to check whether a reference points to a specific instance of an object, which is useful in optimizations, caching, or working with immutable objects.

How does comparison using the identical operator work… - sobes.tech