Generics are a powerful feature of Hack’s type system that allow you to write typesafe code without knowing what types will be flowing through it. A class or function can be generic, which means that it lets the caller specify what types flow through it.
The best examples of generic constructs are arrays and collection classes (see Chapter 5 for more information on collection classes). Without the ability to specify the type of an array’s contents, it would be impossible to infer a type for any value that results from indexing into an array, and setting a value in an array couldn’t be typechecked. These operations are pervasive in PHP and Hack code, and generics let the typechecker understand and verify them.
In this chapter, we’ll look at all the features that generics offer, and how to use them.
We’ll start with a very simple example: a class that just wraps an arbitrary value. You would probably never write such a thing in practice,1 but it’s a good gentle introduction to generics. We’ll use it as a running example throughout this chapter.
To make a class generic, put an angle bracket–enclosed, comma-separated list of type parameters immediately after the name of the class. A type parameter is simply an identifier whose name starts with an uppercase
T. Inside the definition of a generic class, you can use the type parameters in type annotations, in any of the three normal positions (properties, method parameters, and method return types). ...