returning multiple values in Java

后端 未结 6 554
时光说笑
时光说笑 2020-12-11 19:14

Preamble: I am aware of using a list or other collections to return a result but then I have to go through the list plucking the results out: see 2nd example

Preambl

6条回答
  •  情书的邮戳
    2020-12-11 20:08

    Using a generic tuple class is the closest I can imagine. To give an idea, such general purpose class for three return values could look something like this:

    public class T3 {
        A _1;
        B _2;
        C _3;
        T3(A _1, B _2, C _3) {
            this._1 = _1;
            this._2 = _2;
            this._3 = _3;
        }
    }
    

    This allows a one statement constructor on the callee side, for example:

    public T3 getValues() {
        return new T3("string", 0, 'c');
    }
    

    but no holder instance construction by the callee is to be done.

    Each number of return values needs a tuple-class of its own. There might be something like that provided in the Functional Java library. For reference, here's an N-Tuple implementation.

    For the two-valued case java.util.AbstractMap.SimpleEntry would do:

    return new SimpleEntry("string", 0);
    

    Anyhow, I see two important points to consider for multiple return values:

    1. Typed return values
    2. Pointing out the meaning of each return value

    As boring as it is, I'd recommend creating a separate class to hold all the response values and declare that as the method return type. That way the meaning of each value can be highlighted.

提交回复
热议问题