Generics


Generics

Generics is a powerful feature that allows us to define classes, methods, and properties that can be accessed using different data types while maintaining a check of compile-time type security.

Creating Parameter Classes - A generic type is a class or method that is more parameterized than types. The angle brackets () are used to specify the type parameter of the program.

Generic Benefits

  • Typecasting is mandatory- no need to type the object.
  • Type Security- Generic allows only one type of object at a time.
  • Compile Time Safety- Checks the generic code at compile time for the parameterized type to avoid the runtime error.

The Variance

Unlike Java, Kotlin makes arrays default by default. By extension, generic variants in Kotlin remain unchanged. It can be managed both out and in keywords. A standard generic function/class already defined for a particular data type is a property that cannot be changed or accepted by other datatype. It is the supertype of any other data type. The difference is in two ways-

  • Declaration-site Variance (used in and out)
  • Use-site Variance: type projection

The Out keyword - In Kotlin, we can use the generic out keyword, which means we can give this reference to any of its supertypes. Out value can only be produced by a given class but not consumed.

The In Keyword - If we want to assign it to the reference of its subtype, we can use the generic keyword. The in keyword can only be used as a non-generated parameter type.

Covariance - Replacing Covariance subtypes is acceptable, but supertypes are not, meaning that generic function/class may adopt subdivisions of a data type already defined, e.g., A generic class defined for a number can accept int, but a generic class defined for int cannot accept a number.

Contravariance is used to replace a supertype value in subtypes, i.e., the generic function/class may adopt supertypes of a datatype already defined, e.g., a generic class defined for a number cannot accept int, but a generic class defined for int can receive the number.