Chapter 9. Generics

 

This chapter covers

  • Declaring generic functions and classes
  • Type erasure and reified type parameters
  • Declaration-site and use-site variance

You’ve already seen a few code examples that use generics in this book. The basic concepts of declaring and using generic classes and functions in Kotlin are similar to Java, so the earlier examples should have been clear without a detailed explanation. In this chapter, we’ll return to some of the examples and look at them in more detail.

We’ll then go deeper into the topic of generics and explore new concepts introduced in Kotlin, such as reified type parameters and declaration-site variance. These concepts may be novel to you, but don’t worry; the chapter covers them thoroughly.

Reified type parameters allow you to refer at runtime to the specific types used as type arguments in an inline function call. (For normal classes or functions, this isn’t possible, because type arguments are erased at runtime.)

Declaration-site variance lets you specify whether a generic type with a type argument is a subtype or a supertype of another generic type with the same base type and a different type argument. For example, it regulates whether it’s possible to pass arguments of type List<Int> to functions expecting List<Any>. Use-site variance achieves the same goal for a specific use of a generic type and therefore accomplishes the same task as Java’s wildcards.

9.1. Generic type parameters

9.2. Generics at runtime: erased and reified type parameters

9.3. Variance: generics and subtyping

9.4. Summary

sitemap