comparison of instance in dart

immutable instance

  • final properties + constant constructor를 통해서 immutable class instance를 만들 수 있다.
// immutable class
class Person {
  // All properties is final -> cannot be changed after initialization
  final String name;
  const Person(this.name);
}

void main() {
  // comparision and immutability in dart

  final p1 = Person('Alice');
  final p2 = Person('Alice');

  // compare p1 and p2
  print(identical(p1, p2)); // false
  print(p1 == p2); // false
}

  • 비교를 수행하면 reference 비교를 하기 때문에 properties가 완벽히 일치 하더라도 비교의 결과가 false가 된다.
  • 기본 비교 동작을 바꾸고 싶으면 == operator를 override하면 된다. reference 비교가 아닌, properties 값을 비교하도록 override할 수 있다.
// immutable class
class Person {
  // All properties is final -> cannot be changed after initialization
  final String name;
  const Person(this.name);

  @override
  bool operator ==(Object other) {
    if (other is Person) {
      return name == other.name;
    }
    return false;
  }

  @override
  int get hashCode => name.hashCode;
}

void main() {
  // comparision and immutability in dart

  final p1 = Person('Alice');
  final p2 = Person('Alice');

  // compare p1 and p2
  print(identical(p1, p2)); // false
  print(p1 == p2); // false
}

equatable

  • equatable 패키지는 매번 immutable 클래스를 만들 때마다 operator override를 하는 수고를 덜어주주는 패키지다.
  • Equatable class의 props를 override하여 비교를 할 properties를 넣어주면 된다.
// immutable class
import 'package:equatable/equatable.dart';

class Person extends Equatable {
  // All properties is final -> cannot be changed after initialization
  final String name;
  const Person(this.name);

  @override
  List<Object?> get props => [name];
}

void main() {
  // comparision and immutability in dart

  final p1 = Person('Alice');
  final p2 = Person('Alice');

  // compare p1 and p2
  print(identical(p1, p2)); // false
  print(p1 == p2); // false
}