felangel/equatable

Why do we need to compare runtimeType?

anggaaryas opened this issue · 5 comments

Is your feature request related to a problem? Please describe.

Why we need to compare runtimeType? although we have "is" operator to compare the type. From my understanding, Equatable is used for data / field comparison. So, it will be better if we can compare between parent and child class.

Describe the solution you'd like

My solution is to remove runtimeType comparison. But i still not confidence what the cons of removing it.

Describe alternatives you've considered

or maybe we can make equals method accessible, so we can make own comparator.

Additional context

class Foo extends Equatable{
  final int x;
  final int y;

  const Foo(this.x, this.y);

  // @override
  // bool operator ==(Object other) =>
  //     identical(this, other) ||
  //         other is Foo &&                <= No runtimeType comparison
  //             equals(props, other.props);

  @override
  List<Object?> get props => [x,y];
}

class Bar extends Foo{
  const Bar(super.x, super.y);
}

void main(){
  Foo classA = const Foo(10, 100);
  Foo classB = const Bar(10,100);

  print(classA.runtimeType);

  print(classB.runtimeType == Foo); // false
  print(classB is Foo); // true

  print(classB == classA);
}

Hi @anggaaryas 👋
Thanks for opening an issue!

Say we have the following:

import 'package:equatable/equatable.dart';

abstract class Animal extends Equatable {
  @override
  List<Object?> get props => [];
}

class Dog extends Animal {}

class Cat extends Animal {}

void main() {
  final cat = Cat();
  final dog = Dog();
  
  print(cat == dog); // false
}

If we remove the runtimeType check then an instance of a Cat will be considered equal to an instance of a Dog just because they are both of type Animal. Is that what you'd expect?

Hmm OOP comparator...

My use case is only comparing the property. Dont know if this is just rare case.

Oh hey, in my example, i use parent class as type. So it should compare as parent class

'''
Parent obj = Child()
'''

In those cases I suggest you override operator== manually.

Then, make equals method accessible rather than copying the method