Multiple Return Values in Mercury

Java has built-in support for multiple return values through the use of container classes or custom objects. This feature is often used in idiomatic Java, for example, to return both result and error values from a method.

import java.util.AbstractMap.SimpleEntry;

public class MultipleReturnValues {

    // This method returns a SimpleEntry<Integer, Integer> to simulate
    // returning multiple values.
    public static SimpleEntry<Integer, Integer> vals() {
        return new SimpleEntry<>(3, 7);
    }

    public static void main(String[] args) {
        // Here we use the returned SimpleEntry to get both values.
        SimpleEntry<Integer, Integer> result = vals();
        int a = result.getKey();
        int b = result.getValue();
        System.out.println(a);
        System.out.println(b);

        // If you only want a subset of the returned values,
        // you can simply ignore the unwanted value.
        int c = vals().getValue();
        System.out.println(c);
    }
}

To run the program:

$ javac MultipleReturnValues.java
$ java MultipleReturnValues
3
7
7

In Java, we don’t have built-in support for multiple return values like in some other languages. However, we can achieve similar functionality using container classes like SimpleEntry or by creating custom objects. This example demonstrates how to simulate returning multiple values and how to use them in the calling code.

The next topic we’ll explore is variable-length argument lists in Java methods, which provide flexibility in the number of arguments a method can accept.