Skip to content
Advertisement

Multiple assignment at once in java

In python you can do this:

def f():
    return 1, 2, 3
(foo, bar, baz) = f()

Is there an equivalent in java?

Advertisement

Answer

tl;dr: No, there isn’t such a thing in Java.

You can assign initial values to variables like this:

int foo = 1, bar = 2;

But if your want (1, 2, 3) to be the result of a method call, this is not possible in Java. Java does not allow returning multiple values.

Python allows this:

def foo():
    return 1, 2, 3

a, b, c = foo()

The main point, why this does not work in Java is, that the left hand side (LHS) of the assignment must be one variable:

Wrapper wrapper = WrapperGenrator.generateWrapper();

You can not assign to a tuple on the LHS as you can in Python.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement