3

I know Java doesn't support operator overloading, but it seems there are a few operators in other languages that could potentially benefit Java.

Probably my favorite example is the .? operator. Members of an object are only accessed using .? if the object is non-null:

public void example(String arg)
{
    if(arg != null && arg.equals("quit"))
        ...
}

Could be shortened to

public void example(String arg)
{
    if(arg.?equals("quit"))
        ...
}

The .? operator is (at least imho) easy to read, and eliminates some extra code that can sometimes be a detriment to code readability. In some code, there may be multiple checks on the null-state of an object or parameter, and may lead to unnecessary and excessive indentation on entire blocks of code.

Obviously, this would be no revolutionary change, but .? could be universally applied to all subclasses of Object as far as I can see. Am I wrong? And would this go against the logic used to decide that Java won't support operator overloading if it were to be adopted now?

gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
Indigenuity
  • 9,332
  • 6
  • 39
  • 68
  • 3
    No, there's definitely no way this could be integrated into Java as-is. However, several languages that compile to Java or Java bytecode have things like this. – Louis Wasserman Oct 08 '12 at 22:49
  • 1
    The so-called Elvis operator has been proposed for Project Coin: http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000047.html I'm not sure if it will be actually included the 2nd part of the Coin features that will appear in Java 8 though. – Natix Oct 08 '12 at 22:50
  • 1
    The problem is when you try to write the "else" clause... What is the cause of branching to the else? equals() returns false or arg is null? It's typically a wrong "good idea" – Aubin Oct 08 '12 at 22:51
  • 1
    But you can write this if("quit".equals(arg)) cause equals does the null check. But I asume you like suport more operations and methodchaining. – daniel Oct 08 '12 at 22:55
  • Shouldn't that be `?.`? Also, if `arg` is `null`, then `arg?.equals("quit")` will be `null`, but `if` expects a boolean. – ddekany Oct 08 '12 at 23:06
  • Unfortunately Java is quite verbose and conciseness is far from being its forte. And I don't see such features as the one you're describing being easily integrated into it. – b2Wc0EKKOvLPn Oct 08 '12 at 23:06
  • similar to http://stackoverflow.com/questions/4390141/java-operator-for-checking-null-what-is-it-not-ternary – hatchet - done with SOverflow Oct 08 '12 at 23:21

0 Answers0