Tsallaka zuwa abun ciki
Justice Tech School

toString, == and hashCode

Override toString for readable output and == with hashCode for value equality.

Example
class P {
  final int id;
  P(this.id);
  @override String toString() => "P#$id";
  @override bool operator ==(Object o) => o is P && o.id == id;
  @override int get hashCode => id;
}
void main() {
  print(P(1));
  print(P(1) == P(1));
}

Exercise

Text of an object.

String () => "x";

Quiz Test

Why override hashCode with ==?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.