Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I open up my equals statements to accept more than one parameter in Java?

Tags:

java

variables

I have a dream....

In this dream I can replace such constructs as:

if(aLongVariableName.equals(classInstance.aPropertyOfThatInstance) ||  
   aLongVariableName.equals(classInstance.aDifferentProperty)){  
    ...  
}

with

if(aLongVariableName.equals(classInstance.aDifferentProperty || aPropertyOfThatInstance)){ 
   ...  
}

I think the later is more succinct, and easier to read. I'm sure something should be possible as methods can be declared with this kind of signature public void readUnlimitedVariables(Variable ... vars) which takes comma separated variables (as opposed to || or even &&).

This could be opened up to anything that returns a boolean, for instance:

if(myLovelyInstance instanceof AwesomeClass && EpicClass){
    ...
}

where myLovelyInstance implements AwesomeClass && EpicClass

Is this possible in Java? I've not found anything on this so far, by googling or on SO. If it's not in vanilla Java, are there any third party packages like Lombok or lambdaJ that would allow this? If not that either, if this a feature of any language? It seems very intuitive to me but I've not seen it anywhere.

like image 929
AncientSwordRage Avatar asked Jun 29 '13 09:06

AncientSwordRage


1 Answers

Is this possible in Java?

No.

The || operator takes two boolean operands. There's no way to change this. Java does not allow you to overload operators, or to "extend the language syntax" in other ways.

The closest you could get would be to define a overload for equals like this:

public boolean equals(Object ... others) {
    for (Object other: others) {
        if (this.equals(other)) {
            return true;
        }
    }
    return false;
}

and use it like this:

if (aLongVariableName.equals(classInstance.aDifferentProperty,
                             classInstance.anotherProperty)) {
    ...  
}

... which is not really close at all. (And a pretty bad idea as well, IMO)

In fact, I can't think of any language that supports a syntax analogous to what you are proposing. It strikes me that there is too much potential for ambiguity for this to be a sound construct.

like image 116
Stephen C Avatar answered Sep 22 '22 13:09

Stephen C