简体   繁体   English

java相当于ruby的|| =语法

[英]java equivalent of ruby's ||= syntax

I'm brand new to java, coming from a ruby world. 我是一个全新的java,来自红宝石世界。 One thing I love about ruby is the very terse syntax such as ||=. 我喜欢ruby的一件事是非常简洁的语法,例如|| =。

I realize of course that a compiled language is different, but I'm wondering if Java has anything similar. 我当然意识到编译语言是不同的,但我想知道Java是否有类似的东西。

In particular, what I do all the time in ruby is something like: 特别是,我在ruby中所做的一切都是这样的:

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. 只是尝试改进我的Java-fu和语法肯定是我不支持的一个领域。

No, there's not. 不,没有。 But to replace 但要更换

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

something similar is scheduled for Java 7 as Elvis Operator : 类似的东西被安排用于Java 7作为Elvis运营商

somevar = somevar ?: new SomeClass();

As of now, your best bet is the Ternary operator : 截至目前,您最好的选择是Ternary运营商

somevar = (somevar != null) ? somevar : new SomeClass();

我认为你能做的最好的是三元运算符:

someVar = (someVar == null) ? new SomeClass() : someVar;

There is no equivalent in Java. Java中没有等价物。 Part of the reason for this is that null is not considered false . 部分原因是null不被视为false

So, even if there was a logical OR-assignment keyword, you have to remember that: 因此,即使存在逻辑OR分配关键字,您也必须记住:

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

This looks like you could add a method to SomeClass similar to 这看起来像是可以向SomeClass添加类似的方法

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM