Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java equivalent of ruby's ||= syntax

Tags:

java

syntax

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.

like image 726
brad Avatar asked Dec 05 '22 03:12

brad


2 Answers

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();
like image 131
BalusC Avatar answered Dec 19 '22 15:12

BalusC


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

someVar = (someVar == null) ? new SomeClass() : someVar;
like image 37
davidtbernal Avatar answered Dec 19 '22 15:12

davidtbernal