Search⌘ K
AI Features

Creating Generics Classes

Discover how to create generic classes in Kotlin to handle multiple data types safely. Understand how to constrain types using Comparable for ordering and apply these concepts by building a PriorityPair class that stores elements in order.

We'll cover the following...

Often the classes we create deal with specific types; for example, a Book may have title of type String and a list of Authors, a Publisher, and so on. Sometimes though, especially when working with collections, we may not want to tie the members of a class to specific types. For example, a list of Books vs. a list of Authors are both lists. The list should be general enough to support members of either of those types, or other types, but specific enough to disallow, for example, adding an Author to a list of Books. Generics classes are used to create such generalized lists with type safety. Kotlin support for generics is much like the support in Java in many ways, but variance and constraints are declared differently; we discussed these in the context of generic functions in ...