Java equivalent ruby ​​|| = syntax

I am new to java, coming from a ruby ​​world. One thing I love about ruby ​​is a very concise syntax like || =.

I understand, of course, that the compiled language is different, but I wonder if Java has something like that.

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

someVar ||= SomeClass.new 

I think this is incredibly eloquent, but powerful, but so far the only way I can think of to achieve the same is a lot:

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

Just trying to improve my Java-fu and syntax is, of course, one of the areas in which I'm not a professional.

+4
source share
4 answers

No no. But replace

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

something similar is planned for Java 7 as the Elvis Operator :

 somevar = somevar ?: new SomeClass(); 

Currently, the best option is the Ternary operator :

 somevar = (somevar != null) ? somevar : new SomeClass(); 
+10
source

I think the best thing you could do is a triple operator:

 someVar = (someVar == null) ? new SomeClass() : someVar; 
+5
source

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

So, even if there was a logical keyword OR-assign, you must remember that:

 Object x = null; if (!x) { // this doesnt work, null is not a boolean 
+1
source

Looks like you could add SomeClass method similar to

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

And name it like

 someVar = SomeClass.enforce(someVar); 
0
source

Source: https://habr.com/ru/post/1305478/


All Articles