英文:
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)) > 3:
print(f"List is too long ({n} elements, expected <= 3)")
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) > 3) {
System.out.println("List is too long (" + n + " elements, expected <= 3)");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论