Skip to content

Instantly share code, notes, and snippets.

@1cg
Created January 10, 2017 21:31
Show Gist options
  • Save 1cg/b56cc8faf048f317085cc2fa767f8b24 to your computer and use it in GitHub Desktop.
Save 1cg/b56cc8faf048f317085cc2fa767f8b24 to your computer and use it in GitHub Desktop.
Helping understand different notions of equality
// gosu
var x = ...
var y = ...
if( x == y ) {
print("x and y are value equal, including null")
}
if( x === y ) { // note, triple equals!
print("x and y are references equal, including null")
}
if( x.equals( y ) ) {
print("x and y are value equal, unless x is null, in which case there is an NPE in the condition above.")
}
// java
Object x = ...
Object y = ...
if( x == y ) {
print("x and y are references equal, including null")
}
if( x.equals( y ) ) {
print("x and y are value equal, unless x is null, in which case there is an NPE in the condition above.")
}
// correct equality test in java
if( (x == y) || (x != null && x.equals(y)) ) {
print("x and y are value equal and this is null save")
}
// There is a helper for the above code:
if( java.util.Objects.equals(x, y) ) {
print("x and y are value equal and this is null save")
}
// now you can see why gosu is so much better than java... :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment