Generics is a programming style where classes, functions, data structures, or algorithms are written in such a way that the exact type can be specified later. In general, generics provide type safety together with the ability to reuse a particular code structure for various data types.
Generics are present in both Java and Kotlin. They work in a similar way, but Kotlin offers a few improvements over the Java generic type system, such as use-site variance, start-projection syntax, and reified type parameters. We will discuss them in this chapter.
Programmers often need a way to specify that a collection only contains elements of a particular type, such as
Car. Without generics, we would need to separate classes for each data type (
CarList, and so on). Those classes would have a very similar internal implementation, which would only differ in the stored data type. This means that we would need to write the same code (such as...