Skip to content

Commit 06ddd99

Browse files
authored
Create identical-objects-in-dart.dart
1 parent 442af42 commit 06ddd99

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import 'dart:developer' as devtools show log;
2+
3+
extension Log on Object {
4+
void log() => devtools.log(toString());
5+
}
6+
7+
void testIt() {
8+
const person1 = Person(name: 'Vandad', age: 42);
9+
const person2 = Person(name: 'Vandad', age: 42);
10+
const person3 = Person(name: 'Vandad', age: 43);
11+
identical(person1, person2).log(); // true
12+
(person1 == person2).log(); // true
13+
(person1 == person3).log(); // false
14+
(person2 == person3).log(); // false
15+
(person3 == person3).log(); // true
16+
}
17+
18+
@immutable
19+
class Person {
20+
final String name;
21+
final int age;
22+
23+
const Person({
24+
required this.name,
25+
required this.age,
26+
});
27+
28+
@override
29+
bool operator ==(Object other) =>
30+
identical(this, other) ||
31+
other is Person &&
32+
runtimeType == other.runtimeType &&
33+
name == other.name &&
34+
age == other.age;
35+
36+
@override
37+
int get hashCode => Object.hashAll([
38+
name,
39+
age,
40+
]);
41+
}

0 commit comments

Comments
 (0)