August 2017
Intermediate to advanced
440 pages
10h
English
By default, we can parametrize a generic class with any type of type argument. However, we can limit the possible types that can be used as type arguments. To limit the possible values of a type argument, we need to define a type parameter bound. The most common type of constraint is an upper bound. By default, all type parameters have Any? as an implicit upper bound. This is why both the following declarations are equivalent:
class SimpleList<T> class SimpleList<T: Any?>
The preceding bounds mean that we can use any type we want as a type argument for our SimpleList class (including nullable types). This is possible because all nullable and non-nullable types are subtypes of Any?:
class SimpleList<T> class Student
Read now
Unlock full access