operator == method

  1. @override
bool operator ==(
  1. Object other
)
override

Indicates whether some other object is "equal to" this Optional.

The other object is considered equal if:

  • it is also an Optional and;
  • both instances have no value present or;
  • the present values are "equal to" each other via ==.

obj an object to be tested for equality

Returns true if the other object is "equal to" this object otherwise false.

Example

Optional<String> opt1 = Optional.of("hello");
Optional<String> opt2 = Optional.of("hello");
Optional<String> opt3 = Optional.of("world");
Optional<String> empty1 = Optional.empty();
Optional<String> empty2 = Optional.empty();

print(opt1 == opt2); // true (same values)
print(opt1 == opt3); // false (different values)
print(empty1 == empty2); // true (both empty)
print(opt1 == empty1); // false (one has value, one doesn't)

// Works with complex objects
class Person {
  final String name;
  Person(this.name);
  
  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Person && name == other.name;
  
  @override
  int get hashCode => name.hashCode;
}

Optional<Person> person1 = Optional.of(Person("Alice"));
Optional<Person> person2 = Optional.of(Person("Alice"));
print(person1 == person2); // true

Implementation

@override
bool operator ==(Object other) {
  if (identical(this, other)) {
    return true;
  }
  return other is Optional && _value == other._value;
}