Skip to content

Commit f03172c

Browse files
committed
Add hashCode and equals to Option so that Options get handled properly in collections (or tests)
1 parent 08a9e5b commit f03172c

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

core/src/main/java/fj/data/Option.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,22 @@ private static final class None<A> extends Option<A> {
594594
public A some() {
595595
throw error("some on None");
596596
}
597+
598+
@Override
599+
public int hashCode() {
600+
return 31;
601+
}
602+
603+
@Override
604+
public boolean equals(Object obj) {
605+
if (this == obj)
606+
return true;
607+
if (obj == null)
608+
return false;
609+
if (getClass() != obj.getClass())
610+
return false;
611+
return true;
612+
}
597613
}
598614

599615
private static final class Some<A> extends Option<A> {
@@ -606,6 +622,32 @@ private static final class Some<A> extends Option<A> {
606622
public A some() {
607623
return a;
608624
}
625+
626+
@Override
627+
public int hashCode() {
628+
final int prime = 31;
629+
int result = 1;
630+
result = prime * result + ((a == null) ? 0 : a.hashCode());
631+
return result;
632+
}
633+
634+
@Override
635+
public boolean equals(Object obj) {
636+
if (this == obj)
637+
return true;
638+
if (obj == null)
639+
return false;
640+
if (getClass() != obj.getClass())
641+
return false;
642+
Some<?> other = (Some<?>) obj;
643+
if (a == null) {
644+
if (other.a != null)
645+
return false;
646+
} else if (!a.equals(other.a))
647+
return false;
648+
return true;
649+
}
650+
609651
}
610652

611653
public static <T> F<T, Option<T>> some_() {

core/src/test/fj/data/CheckOption.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ object CheckOption extends Properties("Option") {
1616
property("orSome") = forAll((a: Option[Int], n: P1[Int]) =>
1717
a.orSome(n) == (if(a.isNone) n._1 else a.some))
1818

19+
property("hashCode") = forAll((a: Option[Int]) =>
20+
if(a.isNone) a.hashCode == none.hashCode else a.hashCode == some(a.some).hashCode)
21+
22+
property("equals") = forAll((a: Option[Int]) =>
23+
if(a.isNone) a == none else a == some(a.some))
24+
1925
property("mapId") = forAll((a: Option[String]) =>
2026
optionEqual(stringEqual).eq(a.map((x: String) => x), a))
2127

0 commit comments

Comments
 (0)