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?
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)");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With