tags:

views:

141

answers:

4

I'm brand new to java, coming from a ruby world. One thing I love about ruby is the very terse syntax such as ||=.

I realize of course that a compiled language is different, but I'm wondering if Java has anything similar.

In particular, what I do all the time in ruby is something like:

someVar ||= SomeClass.new

I think this is incredibly terse, yet powerful, but thus far the only method I can think of to achieve the same thing is a very verbose:

if(someVar == null){
  someVar = new SomeClass()
}

Just trying to improve my Java-fu and syntax is certainly one area that I'm no pro.

+1  A: 

There is no equivalent in Java. Part of the reason for this is that null is not considered false.

So, even if there was a logical OR-assignment keyword, you have to remember that:

Object x = null;
if (!x) { // this doesnt work, null is not a boolean
Matt
This is one of the things I miss most about C compared to other high level languages if(obj) should evaluate to obj != null. I find it really stupid that it's been removed from us.
Chris Marisic
+5  A: 

I think the best you could do is the ternary operator:

someVar = (someVar == null) ? new SomeClass() : someVar;
notJim
I had to read this 3 times to figure out how it would evaluate somevar = (somevar == null)... Clever, but I wouldn't want to be the guy that gets stuck maintaining this.
David
Hmm, I don't think ternaries are usually considered clever, see http://stackoverflow.com/questions/160218 . I guess you get used to them.
notJim
YIKES! I read that completely wrong... for some reason, my brain read that as "if(somevar=(somevar==null))..." so it looked like it was evaluating the outcome of the assignment operator.
David
+8  A: 

No, there's not. But to replace

if(someVar == null){
  someVar = new SomeClass()
}

something similar is scheduled for Java 7 as Elvis Operator:

somevar = somevar ?: new SomeClass();

As of now, your best bet is the Ternary operator:

somevar = (somevar != null) ? somevar : new SomeClass();
BalusC
I don't generally support the combination of Java and mid-1900's rock-and-roll, but in this case I'll withhold my objection.
Chris
A: 

This looks like you could add a method to SomeClass similar to

public static someClass enforce(someClass x)  {
 someClass r = x.clone();
 if(r == null){
  r = new SomeClass();
 }

 return r;
}

And call it like

someVar = SomeClass.enforce(someVar);
irobeth