Returning multiple values (Groovy)

I sometimes find myself wanting to return multiple values from a function. Here is what can be done with Groovy. I’m pretty sure that the same syntax can be applied to Java code as well though not sure if you can use the def keyword in Java.

    void test_ReturnMultipleValues()
        def (String var1, String var2) = return_multiple_values_function()
        assertTrue("The var1 variable should have hoge1", var1 == 'hoge1')
        assertTrue("The var2 variable should have hoge2", var2 == 'hoge2')

    def return_multiple_values_function()
        return ['hoge1', 'hoge2']

What I think developers should not do is overuse this technique. What if you had 10 values you want to return from a function. I would not use this type of technique, but rather create a class that has all those 10 values and just return an instance of the class from the function. This technique is convenient for a quick function that does some validations or something like that.

Leave a Reply

Your email address will not be published.