#19 Comparision operators with null

brian Wed 28 Dec 2005

The equality and comparision operators always map to equals() or compare(). However since everything is an object, it can lead to some unintuitive behavior when either the lhs or rhs is null (especially when a Bool, Int, or Real). So Fan will allow any of the equality or comparision operators to be used with nulls. In the case of equality two nulls are equal, and in the care of comparision, null is always less than anything else. Some examples:

null < -1    -> true
null > "x"   -> false
null < null  -> false
null <= null -> true

Using other operators such as * / + or - with nulls will result in a NullPointerException (called NullErr in Fan). Plus using the call syntax will result in NullErr, thus a == b is _not_ the same as a.equals(b) when dealing with nulls.

Since these are not straight method calls in the fcode, there is a special opcode for each one:

"CompareEQ      ()        // a.equals(b)",
"CompareNE      ()        // !a.equals(b)",
"Compare        ()        // a.compare(b)",
"CompareLE      ()        // a.compare(b) < 0",
"CompareLT      ()        // a.compare(b) <= 0",
"CompareGT      ()        // a.compare(b) >= 0",
"CompareGE      ()        // a.compare(b) > 0",
"CompareSame    ()        // a === b",

The way I implement this in the Java runtime is to route to static methods in Obj that does the null checks then routes to the virtual instance methods. Doing everything in methods rather than bytecode results in much heavier compression of the bytecode. Strangley enough I'm also seeing faster performance in HotSpot (but that seems odd - need to investigate).

Login or Signup to reply.