Spread, subscript and generics

Three pieces of syntax make a collection read like a value: the spread operator calls a method on every element, the subscript writes one, and a type parameter documents what the collection holds.

Spread on a collection and in a call

spread.groovy

def words = ['ada', 'grace', 'barbara'] println words*.size() println words*.toUpperCase() def add(int... values) { values.sum() } def numbers = [1, 2, 3, 4] println add(*numbers)

groovy spread.groovy

[3, 5, 7]
[ADA, GRACE, BARBARA]
10

*. is collect without a closure, and *values spreads a list into the arguments of a call, which is how a method with varargs takes a collection.

Subscript assignment

subscript.groovy

def letters = ['a', 'b', 'c', 'd'] letters[1] = 'B' letters[2..3] = ['C', 'D'] println letters def ages = [ada: 36] ages['grace'] = 85 println ages

groovy subscript.groovy

[a, B, C, D]
[ada:36, grace:85]

A subscript on the left of an assignment writes one element or a slice; a slice of the wrong size replaces the elements with the new list. The map form adds or replaces one entry.

An immutable view

immutable.groovy

def fixed = [1, 2, 3].asImmutable() println fixed println fixed.getClass().name try { fixed << 4 } catch (UnsupportedOperationException error) { println 'the list is immutable' }

groovy immutable.groovy

[1, 2, 3]
java.util.Collections$UnmodifiableRandomAccessList
the list is immutable

asImmutable() returns a list that refuses every write, which is what a constant of a class should be. The class it returns is an implementation detail; the behaviour is the contract.

Typed collections

generics.groovy

List<List<Integer>> grid = [[1, 2], [3, 4]] Map<String, List<Integer>> byName = [ada: [1, 2], grace: [3]] println grid*.sum() println byName println byName.ada.sum() def element = grid[0][1] println element.getClass().name

groovy generics.groovy

[3, 7]
[ada:[1, 2], grace:[3]]
3
java.lang.Integer

The type parameters are erased at run time, so the last line still names Integer and nothing checks a wrong value at run time. Their value is at compile time: @CompileStatic and an IDE read them, and they document the shape of a nested collection.

Related

Автор статьи: Arthur Isaev