Proposal: Elvis and Other Null-Safe Operators
Winson Quock
winson at atypon.com
Thu Jul 2 13:04:04 PDT 2009
Hi,
I would like to add one small addition to this proposal, if it is not too
late.
Null-safe for-each loop:
List<String> strings = null; // could be null
for (String s : string) { // if list or array is null, do not throw NPE but
skip the loop
...
}
ADVANTAGE:
This replace the current cumbersome and often forgot checks
if (string != null) {
for (String s : string) { // if list or array is null, do not throw NPE
but skip the loop
...
}
}
COMPATIBILITY: This is generally backward compatibility except perhaps some
very arcane codes depending on the throwing of NPE to function correctly,
like
int totalLen = 0;
try {
for (String s : string) { // if list or array is null, do not throw NPE
but skip the loop
totalLen += s.length();
}
} catch (NullPointerException e) {
totalLength = -1;
}
Such practices should be exceeding rare and should not be a concern, or we
can introduce a -X compiler option to restore the original behavior.
ALTERNATIVE: Use a new '?:' operator for null-safe loop, similar to those
other operators proposed by this proposal
for (String s ?: string) { // if list or array is null, do not throw NPE but
skip the loop
...
}
This alleviates the compatibility issue with the arcane case above.
More information about the coin-dev
mailing list