Groovy has it's own
groovy.lang.Tuple
class.We can create an instance of a
Tuple
by providing all elements that need to be in the Tuple
via the constructor. We cannot add new elements to a
Tuple
instance or remove elements. We cannot even change elements in a tuple, so it is completely immutable.
This makes it very useable as return value for a method where we need to return multiple values.
Groovy also provides a
Tuple2
class that can be used for tuple instance of only two elements. The elements are typed in a Tuple2
instance.def tuple = new Tuple('one', 1, new Expando(number: 1))
assert tuple.size() == 3
// To get the value of an element
// at a certain position we use
// the get(index) method.
assert tuple.get(0) == 'one'
// We can use the [] syntax to
// get elements from the tuple.
assert tuple[1] == 1
// We can use methods added to the
// Collection API by Groovy.
assert tuple.last().number == 1
// We cannot add the tuple.
try {
tuple.add('extra')
assert false
} catch (UnsupportedOperationException e) {
println e
assert e
}
// We cannot remove the tuple.
try {
tuple.remove('one')
assert false
} catch (UnsupportedOperationException e) {
println e
assert e
}
// We cannot change the tuple.
try {
tuple[0] = 'new value'
assert false
} catch (UnsupportedOperationException e) {
println e
assert e
}
// Create a Tuple with fixed size
// of 2 elements, a pair.
def pair = new Tuple2('two', 2)
// The Tuple2 class has extra methods
// getFirst() and getSecond() to
// access the values.
assert pair.first == 'two'
assert pair.second == 2
No comments:
Post a Comment