I was reading the source code of the Functional Java library and noticed this:
public static <T> Option<T> none() {
return new None<T>();
}
I was wondering why they don't always return a singleton parameter, specially because of None's equality implementation:
private static final class None<A> extends Option<A> {
...
@Override
public int hashCode() {
return 31;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
return true;
}
}
So I did a search at Functional Java's forum and I found this question and answer:
Is it possible to set this up so it doesn't create a new None for every call to none, can we use a single object to represent None in all cases?
No, but then, who cares? The JIT optimiser can take care of these things quite well nowadays.
My question is how the JIT optimiser handles this in a way that it isn't necessary to return a singleton. I know that object creation is cheap, but I think a singleton would be cheaper and in this case it doesn't add any complexity.