Generic constraints
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 //usage var intList = SimpleList<Int>() var studentList = SimpleList<Student>() var carList = SimpleList<Boolean>()
In some situations, we want to limit the data types that can be used as type...