Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there assignment expression for Java like Walrus operator in Python

Tags:

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?

like image 537
Ramazan Polat Avatar asked Aug 31 '20 08:08

Ramazan Polat


1 Answers

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)");
}
like image 152
blagae Avatar answered Sep 19 '22 22:09

blagae