在Java中是否有类似Python中的“Walrus运算符”的赋值表达式?

huangapple go评论77阅读模式
英文:

Is there assignment expression for Java like Walrus operator in Python

问题

在Python中,您可以像这样将值赋给变量并同时返回它:

a = [1, 2, 3, 4] 
if (n := len(a)) > 3: 
    print(f"List is too long ({n} elements, expected <= 3)") 

在Java中有没有类似的方法?

英文:

In Python, you can assign a value to a variable and return it at the same time like this:

a = [1, 2, 3, 4] 
if (n := len(a)) &gt; 3: 
    print(f&quot;List is too long ({n} elements, expected &lt;= 3)&quot;) 

Is there any way to do this in Java?

答案1

得分: 10

没有单独的运算符,但你绝对可以这样做。但是,你必须在 if 条件之外声明变量:

int[] a = {1, 2, 3, 4};
int n;
if ((n = a.length) > 3) {
    System.out.println("List is too long (" + n + " elements, expected <= 3)");
}
英文:

There's no separate operator, but you can definitely do that. You have to declare the variable outside of the if-condition, though:

int[] a = {1, 2, 3, 4};
int n;
if ((n = a.length) &gt; 3) {
    System.out.println(&quot;List is too long (&quot; + n + &quot; elements, expected &lt;= 3)&quot;);
}

huangapple
  • 本文由 发表于 2020年8月31日 16:38:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63667488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定