Another powerful reason for using tuples is to return multiple values from a single method. Declare the method return type using one of the named tuple types. Then use the from() method to return the values.
private Pair<Boolean, Integer> findCharacter(String string, char c) { int index = string.indexOf(c); if (index == -1) return Tuple.from(false, 0); else return Tuple.from(true, index); }
It is best to use the Variable class and extract() method to retrieve values so that the tuple never needs to be stored when calling the method.
Variable<Boolean> found = new Variable<Boolean>(); Variable<Integer> index = new Variable<Integer>(); findCharacter("Hello, world", 'w'). extract(found).extract(index); if (found.get()) { int i = index.get(); // i = 7 }
If you would rather return values via parameters, the Variable class can be used instead of the traditional single-valued array. Use the set() method to assign a value to a Variable.
private boolean findCharacter(String string, char c, Variable<Integer> indexRef) { int index = string.indexOf(c); if (index == -1) return false; else { indexRef.set(index); return true; } }
Variable<Integer> index = new Variable<Integer>(); if (findCharacter("Hello, world", 'w', index)) { int i = index.get(); // i = 7 }