Generalizing types
We have previously taken a look at the concepts of traits, which allow us to standardize the behavior of multiple types. We were then able to define functions that can work with any type that implements the trait. We can go one step further, however, and implement types and functions that are compatible with all data types, not just standardized ones. In this chapter, we will start with types that can be parametrized with other types.
Take a look at the following type called Tuple. A tuple is a type that holds two values, no matter their type. In our example, the types of both values are passed as the type parameters called First and Second. The list of type parameters is defined in angled brackets after the name of the type. The types that are passed into our custom type are only valid (accessible) inside the body of the type definition. The types passed in as arguments are referred to as placeholders in Rouge. Placeholder types have to be treated as black boxes, meaning you cannot make any assumptions about their contents or behavior. This limitation entails that we can only move around or store values of placeholder types, not interact with them.
The moment we instantiate a type with placeholders is the moment we need to pass in the types. Types are passed in angled brackets between the name of the type and the parentheses in which the regular parameters are specified. In the following example, the Tuple type is used to represent a set of coordinates; therefore, the placeholders First and Second are set to Number.
Admittedly, you have known how to define a type that can hold two numbers for several chapters now. However, the benefit of using a generalized type such as Tuple over, for instance, a Coordiante type which always stores two numbers, is that Tuple can be reused in many places, where it represents something entirely different. This benefit should become increasingly clear to you in the following chapters, where you will be introduced to several useful types from the standard library that make use of placeholders. You will also learn how to define functions that can be parametrized with placeholders.