Bounded polymorphism
Functions that are generic for any type are useful, but somewhat limited. Often we will find ourselves wanting to write functions that are generic for some types that share a common characteristic. For instance, we might want to define a function to return the minimum of two values, for any values that support some notion of comparability.
We'd start by writing a function that has a type parameter representing the types of the two values being compared. But how can we compare these values, since they could be instances of anything, including Any
itself? Since Any
has no comparison function, we wouldn't have a way to compare the two values.
The solution is to restrict the types to those that support the functions we need to invoke; this way, the compiler knows that no matter what the runtime type of the arguments is, those functions must be available. Therefore, it allows us to invoke those functions. This is called bounded polymorphism.
Upper bounds
Kotlin supports...