9.4 Appendables
An appendable value is one that supports ++. Maps, lists, arrays, sets, strings, and byte strings are all appendable, as are instances of classes that implement Appendable.
operator | ||
| ||
operator | ||
| ||
operator | ||
| ||
operator | ||
| ||
operator | ||
| ||
operator | ||
| ||
| ||
operator | ||
| ||
operator | ||
|
In the case of maps, mappings for keys in v2 replace ones that exist already in v1. In the case of sets, the new set has all of the elements of v1 and v2. In the case of lists, pair lists, strings, and byte strings, the elements of v1 appear first in the result followed by the elements of v2.
The combination map_expr ++ {key_expr: val_expr} or set_expr ++ {elem_expr} is recognized by the compiler and turned into an efficient functional update of the map or set produced by map_expr or set_expr, as opposed to creating an intermediate map or set.
When v1 is an instance of a class that implements Appendable, then v2 must be an instance of the same class or a subclass that inherits the same append method.
The use_static declaration constrains ++ to work only when the left-hand argument has static information indicating that it satisfies Appendable.
> {1, 2, 3} ++ {"four", "five"}
{1, 2, 3, "five", "four"}
> [1, 2, 3] ++ [4, 5]
[1, 2, 3, 4, 5]
"hello world"
interface | |
An interface that a class can implement (publicly or privately) to make instances of the class work with ++. As an annotation, Appendable matches all appendable objects, not just instances of classes that publicly implement the Appendable interface.
The interface has a single abstract method:
append(other) —
the other value is the right-hand argument to ++, and it is always an instance of the same class or a subclass that inherits the same append implementation.
There is no requirement on the result of the append method, but by convention, the result is the same class as the arguments.
class Posn(x, y):
> Posn(1, 2) ++ Posn(200, 100)
Posn(201, 102)