Chapter 2. Generics
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.
Introductory Example
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 ...
Get Hack and HHVM now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.