Multiple Return Values in Squirrel

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

import java.util.Arrays;

public class MultipleReturnValues {
    
    // This method returns an array of integers
    public static int[] vals() {
        return new int[]{3, 7};
    }
    
    public static void main(String[] args) {
        // Here we use the returned array and assign its values
        int[] result = vals();
        int a = result[0];
        int b = result[1];
        System.out.println(a);
        System.out.println(b);
        
        // If you only want a subset of the returned values,
        // you can simply ignore the unwanted values
        int c = vals()[1];
        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. Instead, we use an array to simulate this behavior. The vals() method returns an array of integers, which we then unpack in the main method.

If you only want a subset of the returned values, you can simply access the specific index of the array, ignoring the other values. In Java, there’s no direct equivalent to the blank identifier (_) used in some other languages, so we simply don’t assign the unwanted values.

Accepting a variable number of arguments is another feature available in Java; we’ll look at this next with the use of varargs.