Elegant ways to return multiple values from a function

后端 未结 14 878
梦谈多话
梦谈多话 2020-12-15 03:49

It seems like in most mainstream programming languages, returning multiple values from a function is an extremely awkward thing.

The typical soluti

14条回答
  •  眼角桃花
    2020-12-15 04:35

    As for Java, see Bruce Eckel's Thinking in Java for a nice solution (pp. 621 ff).

    In essence, you can define a class equivalent to the following:

    public class Pair {
        public final T left;
        public final U right;
        public Pair (T t, U u) { left = t; right = u; }
    }
    

    You can then use this as the return type for a function, with appropriate type parameters:

    public Pair getAnswer() {
        return new Pair("the universe", 42);
    }
    

    After invoking that function:

    Pair myPair = getAnswer();
    

    you can refer to myPair.left and myPair.right for access to the constituent values.

    There are other syntactical sugar options, but the above is the key point.

提交回复
热议问题